234

How to convert calendar date to yyyy-MM-dd format.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();             
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String date1 = format1.format(date);            
Date inActiveDate = null;
try {
    inActiveDate = format1.parse(date1);
} catch (ParseException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

This will produce inActiveDate = Wed Sep 26 00:00:00 IST 2012. But what I need is 2012-09-26. My purpose is to compare this date with another date in my database using Hibernate criteria. So I need the date object in yyyy-MM-dd format.

5
  • 5
    You're code is confusing. Are you trying to format a Date to yyyy-MM-dd or parse a String from yyyy-MM-dd to a Date value?? To format the date, simply use format1.format(date), to parse it, use format1.parse(someStringValueInTheCorrectFormat) Commented Sep 25, 2012 at 4:01
  • I have edited my question.. Sorry for the previous mistake..
    – nr.iras.sk
    Commented Sep 25, 2012 at 4:16
  • 9
    one liner: ( new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" ) ).format( Calendar.getInstance().getTime() ); Commented Jun 5, 2014 at 10:11
  • Possible duplicate of want current date and time in “dd/MM/yyyy HH:mm:ss.SS” format
    – Anonymous
    Commented Sep 24, 2018 at 20:59
  • @IwanAucamp: you are creating a new instance on every call — this is wasteful because the formatter can be a constant and can only be created once (given that you don't need thread safety as SDF is not thread-safe).
    – ccpizza
    Commented Sep 11, 2020 at 15:23

11 Answers 11

379

A Java Date is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.

When you use something like System.out.println(date), Java uses Date.toString() to print the contents.

The only way to change it is to override Date and provide your own implementation of Date.toString(). Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).

Java 8+

LocalDateTime ldt = LocalDateTime.now().plusDays(1);
DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(ldt);
// Output "2018-05-12T17:21:53.658"

String formatter = formmat1.format(ldt);
System.out.println(formatter);
// 2018-05-12

Prior to Java 8

You should be making use of the ThreeTen Backport

The following is maintained for historical purposes (as the original answer)

What you can do, is format the date.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"

String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2012-09-26"

System.out.println(format1.parse(formatted));
// Output "Wed Sep 26 00:00:00 EST 2012"

These are actually the same date, represented differently.

11
  • 1
    Kind of, but it's much easier with Calendar Commented Sep 25, 2012 at 4:50
  • 1
    Anyway to remove timezone completely from from this calender object?
    – nr.iras.sk
    Commented Sep 25, 2012 at 5:24
  • 2
    If you're really serious about date/time manipulation, take a look at Joda Time, it's significantly easier then messing around with Calendar Commented Sep 25, 2012 at 5:30
  • 2
    @n13 if the question was about database date manipulation or even time manipulation I might agree with you. The question was how to represent a date value in particular date format Commented May 5, 2013 at 3:12
  • 1
    Nicely structured answer - this is basically Model(Date)-View(Format) separation.
    – YoYo
    Commented Feb 1, 2016 at 21:44
22

Your code is wrong. No point of parsing date and keep that as Date object.

You can format the calender date object when you want to display and keep that as a string.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();             
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");          
String inActiveDate = null;
try {
    inActiveDate = format1.format(date);
    System.out.println(inActiveDate );
} catch (ParseException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}
13

java.time

The answer by MadProgrammer is correct, especially the tip about Joda-Time. The successor to Joda-Time is now built into Java 8 as the new java.time package. Here's example code in Java 8.

When working with date-time (as opposed to local date), the time zone in critical. The day-of-month depends on the time zone. For example, the India time zone is +05:30 (five and a half hours ahead of UTC), while France is only one hour ahead. So a moment in a new day in India has one date while the same moment in France has “yesterday’s” date. Creating string output lacking any time zone or offset information is creating ambiguity. You asked for YYYY-MM-DD output so I provided, but I don't recommend it. Instead of ISO_LOCAL_DATE I would have used ISO_DATE to get this output: 2014-02-25+05:30

ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTime = ZonedDateTime.now( zoneId );

DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_LOCAL_DATE; // Caution: The "LOCAL" part means we are losing time zone information, creating ambiguity.
String output = formatterOutput.format( zonedDateTime );

Dump to console…

System.out.println( "zonedDateTime: " + zonedDateTime );
System.out.println( "output: " + output );

When run…

zonedDateTime: 2014-02-25T14:22:20.919+05:30[Asia/Kolkata]
output: 2014-02-25

Joda-Time

Similar code using the Joda-Time library, the precursor to java.time.

DateTimeZone zone = new DateTimeZone( "Asia/Kolkata" );
DateTime dateTime = DateTime.now( zone );
DateTimeFormatter formatter = ISODateTimeFormat.date();
String output = formatter.print( dateTime );

ISO 8601

By the way, that format of your input string is a standard format, one of several handy date-time string formats defined by ISO 8601.

Both Joda-Time and java.time use ISO 8601 formats by default when parsing and generating string representations of various date-time values.

6

java.util.Date object can't represent date in custom format instead you've to use SimpleDateFormat.format method that returns string.

String myString=format1.format(date);
6
public static void main(String[] args) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, month, date);
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM dd");
    String formatted = format1.format(cal.getTime());
    System.out.println(formatted);
}
1
3
public static String ThisWeekStartDate(WebDriver driver) {
        Calendar c = Calendar.getInstance();
        //ensure the method works within current month
        c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        System.out.println("Before Start Date " + c.getTime());
        Date date = c.getTime();

          SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");

          String CurrentDate = dfDate.format(date);
          System.out.println("Start Date " + CurrentDate);
          return CurrentDate;

    }
    public static String ThisWeekEndDate(WebDriver driver) {

        Calendar c = Calendar.getInstance();
        //ensure the method works within current month
        c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
        System.out.println("Before End Date " + c.getTime());
        Date date = c.getTime();

          SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");

          String CurrentDate = dfDate.format(date);
          System.out.println("End Date " + CurrentDate);
          return CurrentDate;
    }
2

In order to parse a java.util.Date object you have to convert it to String first using your own format.

inActiveDate = format1.parse(  format1.format(date)  );

But I believe you are being redundant here.

2
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 7);
Date date = c.getTime();
SimpleDateFormat ft = new SimpleDateFormat("MM-dd-YYYY");
JOptionPane.showMessageDialog(null, ft.format(date));

This will display your date + 7 days in month, day and year format in a JOption window pane.

1

My answer is for kotlin language.

You can use SimpleDateFormat to achieve the result:

val date = Date(timeInSec)
val formattedDate = SimpleDateFormat("yyyy-MM-dd", Locale("IN")).format(date)

for details click here.

OR

Use Calendar to do it for you:

val dateObject = Date(timeInMillis)
val calendarInstance = Calendar.getInstance()
calendarInstance.time = dateObject
val date = "${calendarInstance.get(Calendar.YEAR)}-${calendarInstance.get(Calendar.MONTH)}-${calendarInstance.get(Calendar.DATE)}"

For more details check this answer.

2
  • I know that Calendar and SimpleDateFormat were asked about, but that was in 2012, and surely no one needs them in 2022 since they are poorly designed and their replacement, java.time, came out more than 8 years ago.
    – Anonymous
    Commented Jun 14, 2022 at 16:09
  • @OleV.V. I disagree with "not needed". If it is still in existence there must be need. Anyway thanks for mentioning java.time package.
    – Mr. Techie
    Commented Jun 14, 2022 at 19:31
0

I found this code where date is compared in a format to compare with date field in database...may be this might be helpful to you...

When you convert the string to date using simpledateformat, it is hard to compare with the Date field in mysql databases.

So convert the java string date in the format using select STR_to_DATE('yourdate','%m/%d/%Y') --> in this format, then you will get the exact date format of mysql date field.

http://javainfinite.com/java/java-convert-string-to-date-and-compare/

1
  • 3
    Link-only answers are discouraged on StackOverflow because of link-rot and other issues. Can you give a summary of the information with key points? Commented Aug 19, 2015 at 19:26
-1

I don't know about y'all, but I always want this stuff as a one-liner. The other answers are fine and dandy and work great, but here is it condensed to a single line. Now you can hold less lines of code in your mind :-).

Here is the one Liner:

String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
2
  • 1
    Please don’t teach the young ones to use the long outdated and notoriously troublesome SimpleDateFormat class. At least not as the first option. And not without any reservation. We have so much better in java.time, the modern Java date and time API, and its DateTimeFormatter. Yes, you can use it on Android. For older Android look into desugaring. A java.time one-liner is String currentDate = LocalDate.now().toString();. Shorter than yours. :-)
    – Anonymous
    Commented Sep 2, 2022 at 18:01
  • 1
    Sun, Oracle, and the JCP community all gave up on the terribly flawed legacy classes when they adopted JSR 310 defining the java.time classes. I suggest you do the same. Commented Sep 3, 2022 at 7:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.