224

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.

entpnerd
  • 8,063
  • 5
  • 36
  • 60
Sarika.S
  • 6,786
  • 27
  • 72
  • 103
  • 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)` – MadProgrammer Sep 25 '12 at 04:01
  • I have edited my question.. Sorry for the previous mistake.. – Sarika.S Sep 25 '12 at 04:16
  • 9
    one liner: `( new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" ) ).format( Calendar.getInstance().getTime() );` – Iwan Aucamp Jun 05 '14 at 10:11
  • Possible duplicate of [want current date and time in “dd/MM/yyyy HH:mm:ss.SS” format](https://stackoverflow.com/questions/8745297/want-current-date-and-time-in-dd-mm-yyyy-hhmmss-ss-format) – Ole V.V. Sep 24 '18 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 Sep 11 '20 at 15:23

9 Answers9

355

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.

MadProgrammer
  • 323,026
  • 21
  • 204
  • 329
  • Is it possible to get tomorrows date without using calendar class? – Sarika.S Sep 25 '12 at 04:43
  • 1
    Kind of, but it's much easier with `Calendar` – MadProgrammer Sep 25 '12 at 04:50
  • 1
    Anyway to remove timezone completely from from this calender object? – Sarika.S Sep 25 '12 at 05:24
  • No, not really, you could try creating a Calendar with a GMT time zone (0 millisecond offset) using something like `Calendar.getInstance(TimeZone.getTimeZone("GMT"))` – MadProgrammer Sep 25 '12 at 05:29
  • 2
    If you're really serious about date/time manipulation, take a look at [Joda Time](http://joda-time.sourceforge.net/), it's significantly easier then messing around with `Calendar` – MadProgrammer Sep 25 '12 at 05:30
  • I want to point out that this code is wrong in general - its output depends on what timezone of the machine it is running on. Very often, that time zone happens to be the same time zone as the DB dates. But sometimes, they're not the same. A date like 2012-09-09 is ambiguous if you don't define the time zone. A timestamp is absolute. Anyway if you do cal.add, it's using the system time zone - may or may not be correct but is certainly not good code. – n13 May 05 '13 at 01:34
  • 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 – MadProgrammer May 05 '13 at 03:12
  • @IwanAucamp one liners aren't always practical, especially when trying to explain a concept. You may want to reuse the formatter for example, they can also be difficult to read, for example – MadProgrammer Jun 05 '14 at 10:12
  • 1
    Nicely structured answer - this is basically Model(Date)-View(Format) separation. – YoYo Feb 01 '16 at 21:44
  • Could anyone please explain why this answer would deserve a downvote? "It's not using the new shiny Java 8 API" - It was 2012 for crying out loud – MadProgrammer Feb 11 '16 at 20:03
  • I love the idea that this should draw a downvote - can someone please explain how this is not answering the OPs question or how it could be done better?! – MadProgrammer Jun 19 '18 at 21:38
20

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();
}
MadProgrammer
  • 323,026
  • 21
  • 204
  • 329
Niroshan Abayakoon
  • 895
  • 1
  • 10
  • 22
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.

Community
  • 1
  • 1
Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
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);
kv-prajapati
  • 90,019
  • 18
  • 141
  • 178
3
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);
}
Petr
  • 31
  • 1
  • 2
    Welcome to SO. Please add some context/explanation, as code only answers do not fulfill our standards. See https://stackoverflow.com/help/how-to-answer – Uwe Allner Sep 26 '17 at 11:15
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.

ElderMael
  • 6,769
  • 5
  • 31
  • 51
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.

Drew
  • 302
  • 3
  • 9
1
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;
    }
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/

JavaLearner
  • 230
  • 1
  • 10
  • 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? – Basil Bourque Aug 19 '15 at 19:26