214

I wrote the following code

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

I want the current date in string format, like

28-Dec-2011

so that I can set it into a TextView.

Ryan M
  • 18,333
  • 31
  • 67
  • 74
Chatar Veer Suthar
  • 15,541
  • 26
  • 90
  • 154
  • 1
    While using the `DateFormat` class was OK when this question was asked in 2011, that class and its subclass `SimpleDateFormat` were always troublesome and are now long outdated. I recommend you don’t use them and instead look into [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jul 13 '19 at 11:25

31 Answers31

441

You can use the SimpleDateFormat class for formatting date in your desired format.

Just check this link where you get an idea for your example.

For example:

String dateStr = "04/05/2010"; 
 
SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy"); 
Date dateObj = curFormater.parse(dateStr); 
SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy"); 
 
String newDateStr = postFormater.format(dateObj); 

Update:

The detailed example is here, I would suggest you go through this example and understand the concept of SimpleDateFormat class.

Final Solution:

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

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
String formattedDate = df.format(c);
Pooja
  • 475
  • 5
  • 14
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
  • you may want to use the System.currentTimeMillis() method or the Data class instead f the Calendar class. Should be quicker. http://stackoverflow.com/questions/368094/system-currenttimemillis-vs-new-date-vs-calendar-getinstance-gettime – cjayem13 Aug 31 '14 at 02:29
  • 2
    This requires API 24! – ueen Jun 05 '19 at 13:21
  • 1
    FYI, the terribly troublesome date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jul 14 '19 at 01:14
  • @ueen Please import from java package not from android. – Sadda Hussain Aug 24 '19 at 06:32
  • Works fines? Currently? (2020) – luke cross May 21 '20 at 19:52
180

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());
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
  • 9
    You should change it to: String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date()); – Bart Burg Apr 10 '14 at 09:56
  • 1
    Wow, thank you! This worked, although I believe I may have found out why the date on my virtual device was showing one day before, probably because the date on the virtual machine wasn't right. When tested on an actual phone, it worked wonders. So thank you @Pratik – wesley franks Nov 01 '15 at 18:59
31

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); 
}
Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75
Graham Smith
  • 25,627
  • 10
  • 46
  • 69
12
 public String giveDate() {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy");
    return sdf.format(cal.getTime());
 }
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
Kamal
  • 1,415
  • 13
  • 24
11

try this,

SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
Date myDate = new Date();
String filename = timeStampFormat.format(myDate);
Deepzz
  • 4,573
  • 1
  • 28
  • 52
Lucifer
  • 29,392
  • 25
  • 90
  • 143
9
CharSequence s  = DateFormat.getDateInstance().format("MMMM d, yyyy ");

You need an instance first

Marthyn Olthof
  • 1,029
  • 11
  • 22
8

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);
SoVinceble
  • 486
  • 5
  • 10
7
 String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

// import Date class as java.util

IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
arshad shaikh
  • 673
  • 8
  • 11
5

A simple tweak to Paresh's solution:

Date date = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(date);
cNgamba
  • 111
  • 1
  • 10
5
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String date = df.format(Calendar.getInstance().getTime());
Zeeshan Ali
  • 2,211
  • 4
  • 18
  • 25
5
 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();
Md Tariqul Islam
  • 2,736
  • 1
  • 20
  • 35
indrajeet jyoti
  • 431
  • 6
  • 8
  • Is it contributing anything substantial towards the question (*I want current date in string format, like `28-Dec-2011`*) that isn’t already in the other answers? In any case it is still using the notoriously troublesome and long outdated `SimpleDateFormat` class. Please, we don’t need any more answers doing that. – Ole V.V. Jul 13 '19 at 11:22
  • it's working for best practice add the second parameter locale SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH); – Rucha Bhatt Joshi Apr 22 '20 at 13:46
5

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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Very good answer! But how can I convert ThreeTen LocalDateTime to Date? I'm using Firebase, and a prerequisite for saving timestamp is Date object. – H.Karatsanov Jul 03 '20 at 13:01
  • @H.Karatsanov If using the backport: `DateTimeUtils.toDate(yourLocalDateTime.atZone(ZoneId.systemDefault()).toInstant())`. If using the built-in java.time: `Date.from(yourLocalDateTime.atZone(ZoneId.systemDefault()).toInstant())`. See [Converting between java.time.LocalDateTime and java.util.Date](https://stackoverflow.com/questions/19431234/converting-between-java-time-localdatetime-and-java-util-date). The authoritative answer by JodaStephen is there, and also [an answer showing the use of the backport](https://stackoverflow.com/a/52196587/5772882). – Ole V.V. Jul 04 '20 at 04:19
5

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;
}
İsmail Y.
  • 3,579
  • 5
  • 21
  • 29
4

The below code displays the both time and date

Calendar cal = Calendar.getInstance();
cal.getTime().toString();
3
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();        
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
Vinayak
  • 425
  • 4
  • 6
3
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);
barbsan
  • 3,418
  • 11
  • 21
  • 28
rhaldar
  • 1,075
  • 10
  • 6
2

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()));
Android Dev
  • 1,496
  • 1
  • 13
  • 25
  • Nice one liner and works on lower Sdks. A few characters shorter DateFormat.format("dd-MM-yyyy", new java.util.Date()).toString() – Jeffrey Aug 17 '18 at 06:44
2
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...

Yannis
  • 1,682
  • 7
  • 27
  • 45
Fatima
  • 21
  • 2
2

if you just want to get the date just put code like this

Calendar.getInstance().getTime();
Vanya Rachel
  • 1,329
  • 1
  • 18
  • 20
1

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 ... :)

vijay saini
  • 361
  • 3
  • 6
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` and `DateFormat` classes. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. May 19 '20 at 03:50
  • 1
    @OleV.V. Can you explain whats so terrible about this method? I am new to android and java and it does exactly what I need it to, so what is so troublesome about it? – d0rf47 Oct 22 '20 at 19:34
  • @d0rf47 From Oracle: [Why do we need a new date and time library?](https://www.oracle.com/technical-resources/articles/java/jf14-date-time.html) Also [Still using java.util.Date? Don’t!](https://programminghints.com/2017/05/still-using-java-util-date-dont/) – Ole V.V. Oct 22 '20 at 20:42
1

Tried with this approch it worked for me.

val df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault()) // pass the format pattern that you like and done.
println(df.format(Date()))
1
In Kotlin you can use this code : - 

Simple only need to change date format to this "dd-MM-yyyy" 
val d = Date()
val str: CharSequence = DateFormat.format("dd-MM-yyyy", d.getTime())
Log.e("", str.toString())
    
In Java You use this code: - 
    
Date date = new Date();
CharSequence str  = DateFormat.format("dd-MM-yyyy", date.getTime());
Log.e("Date", str.toString())
Safal Bhatia
  • 245
  • 2
  • 6
1
LocalDateTime ldt2 = LocalDateTime.now();
String year = ldt2.getYear()+"";
String month = ldt2.getMonthValue()+"";
String date = ldt2.getDayOfMonth()+"";
String hour = ldt2.getHour()+"";
String minute = ldt2.getMinute()+"";
String secs = ldt2.getSecond()+"";
Anand
  • 4,355
  • 2
  • 35
  • 45
0

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());
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
Ivo Stoyanov
  • 16,256
  • 8
  • 62
  • 65
0
  public static String getDateTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy HH:mm:ss", Locale.getDefault());
        Date date = new Date();
        return simpleDateFormat.format(date);
    }
0

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

Community
  • 1
  • 1
Amitsharma
  • 1,577
  • 1
  • 17
  • 29
0

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.

Muskovets
  • 449
  • 8
  • 16
0

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);
Savita Sharma
  • 344
  • 3
  • 9
0

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.

Farshid Ahmadi
  • 437
  • 6
  • 23
0

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")}
creativecoder
  • 1,470
  • 1
  • 14
  • 23
-1

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);
Coincoin
  • 27,880
  • 7
  • 55
  • 76
dondondon
  • 881
  • 8
  • 4