[android] How can I get current date in Android?

I wrote the following code

Date d = new Date();
CharSequence s  = DateFormat.format("MMMM d, yyyy ", d.getTime());

But is asking me parameter, I want current date in string format,

like

28-Dec-2011

so that I can set over TextView,

explain a bit, if you think something is necessary, I am new to Android Development.

This question is related to android date simpledateformat android-date

The answer is


Date c = Calendar.getInstance().getTime();
System.out.println("Current time => " + c);

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c);

This one is the best answer...


Works like a charm and converts to String as a bonus ;)

SimpleDateFormat currentDate = new SimpleDateFormat("dd/MM/yyyy");
      Date todayDate = new Date();
    String thisDate = currentDate.format(todayDate);

You can use following code to get a date in the format you want.

String date = String.valueOf(android.text.format.DateFormat.format("dd-MM-yyyy", new java.util.Date()));

The simplest way to get the current date in current locale (device locale!) :

String currentDate = DateFormat.getDateInstance().format(Calendar.getInstance().getTime());

If you want to have the date in different styles use getDateInstance(int style):

DateFormat.getDateInstance(DateFormat.FULL).format(Calendar.getInstance().getTime());

Other styles: DateFormat.LONG, DateFormat.DATE_FIELD, DateFormat.DAY_OF_YEAR_FIELD, etc. (use CTRL+Space to see all of them)

If you need the time too:

String currentDateTime = DateFormat.getDateTimeInstance(DateFormat.DEFAULT,DateFormat.LONG).format(Calendar.getInstance().getTime());

I am providing the modern answer.

java.time and ThreeTenABP

To get the current date:

    LocalDate today = LocalDate.now(ZoneId.of("America/Hermosillo"));

This gives you a LocalDate object, which is what you should use for keeping a date in your program. A LocalDate is a date without time of day.

Only when you need to display the date to a user, format it into a string suitable for the user’s locale:

    DateTimeFormatter userFormatter
            = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
    System.out.println(today.format(userFormatter));

When I ran this snippet today in US English locale, output was:

July 13, 2019

If you want it shorter, specify FormatStyle.MEDIUM or even FormatStyle.SHORT. DateTimeFormatter.ofLocalizedDate uses the default formatting locale, so the point is that it will give output suitable for that locale, different for different locales.

If your user has very special requirements for the output format, use a format pattern string:

    DateTimeFormatter userFormatter = DateTimeFormatter.ofPattern(
            "d-MMM-u", Locale.forLanguageTag("ar-AE"));

13-???-2019

I am using and recommending java.time, the modern Java date and time API. DateFormat, SimpleDateFormat, Date and Calendar used in the question and/or many of the other answers, are poorly designed and long outdated. And java.time is so much nicer to work with.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links


A simple tweak to Paresh's solution:

Date date = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(date);

This is the code I used:

final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);

// Set current date into textview
tvDisplayDate.setText(new StringBuilder()
    .append(month + 1).append("-") // Month is 0 based, add 1
    .append(day).append("-")
    .append(year).append("   Today is :" + thursday ) );

// Set current date into datepicker
dpResult.init(year, month, day, null);

Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
String date = day + "/" + (month + 1) + "/" + year;

Log.i("TAG", "--->" + date);

This method can use for to get current date from the system.

public static String getCurrentDateAndTime(){
    Date c = Calendar.getInstance().getTime();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
    String formattedDate = simpleDateFormat.format(c);
    return formattedDate;
}

I've already used this:

Date What_Is_Today=Calendar.getInstance().getTime();
SimpleDateFormat Dateformat = new SimpleDateFormat("dd-MM-yyyy");
String Today=Dateformatf.format(What_Is_Today);

Toast.makeText(this,Today,Toast.LENGTH_LONG).show();

at first I get time, then I declared a Simple Date Format (to get date like: 19-6-2018) then I use format to change date to string.


Calendar cal = Calendar.getInstance();      
Calendar dt = Calendar.getInstance(); 
dt.clear();
dt.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),cal.get(Calendar.DATE)); 
return dt.getTime();        

try with this link of code this is absolute correct answer for all cases all over date and time. or customize date and time as per need and requirement of app.

try with this link .try with this link


SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String date = df.format(Calendar.getInstance().getTime());

In Kotlin

https://www.programiz.com/kotlin-programming/examples/current-date-time

fun main(args: Array<String>) {

val current = LocalDateTime.now()

val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
val formatted = current.format(formatter)

println("Current Date and Time is: $formatted")}

I wrote calendar app using CalendarView and it's my code:

CalendarView cal = (CalendarView) findViewById(R.id.calendar);
cal.setDate(new Date().getTime());

'calendar' field is my CalendarView. Imports:

import android.widget.CalendarView;
import java.util.Date;

I've got current date without errors.


  public static String getDateTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy HH:mm:ss", Locale.getDefault());
        Date date = new Date();
        return simpleDateFormat.format(date);
    }

 public String giveDate() {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy");
    return sdf.format(cal.getTime());
 }

try this,

SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
Date myDate = new Date();
String filename = timeStampFormat.format(myDate);

The below code displays the both time and date

Calendar cal = Calendar.getInstance();
cal.getTime().toString();

 String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

// import Date class as java.util


Its simple one line code for get current Date in this yyyy-MM-dd format you can use your format that you want :

String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());

CharSequence s  = DateFormat.getDateInstance().format("MMMM d, yyyy ");

You need an instance first


This is the code i used:

             Date date = new Date();  // to get the date
             SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); // getting date in this format
             String formattedDate = df.format(date.getTime());
             text.setText(formattedDate);

 public static String getcurrentDateAndTime(){

        Date c = Calendar.getInstance().getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String formattedDate = simpleDateFormat.format(c);
        return formattedDate;
    }

// String currentdate=  getcurrentDateAndTime();

just one line code to get simple Date format :

SimpleDateFormat.getDateInstance().format(Date())

output : 18-May-2020

SimpleDateFormat.getDateTimeInstance().format(Date())

output : 18-May-2020 11:00:39 AM

SimpleDateFormat.getTimeInstance().format(Date())

output : 11:00:39 AM

Hope this answer is enough to get this Date and Time Format ... :)


This is nothing to do with android as it is java based so you could use

private String getDateTime() { 
   DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
   Date date = new Date(); 
   return dateFormat.format(date); 
}

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to simpledateformat

How to convert an Instant to a date format? Get Date Object In UTC format in Java How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss) How to convert date to string and to date again? Java Convert GMT/UTC to Local time doesn't work as expected Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST SimpleDateFormat parse loses timezone java.text.ParseException: Unparseable date Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss SimpleDateFormat returns 24-hour date: how to get 12-hour date?

Examples related to android-date

How can I get current date in Android? how to convert milliseconds to date format in android? Display the current time and date in an Android application