[java] Calendar date to yyyy-MM-dd format in java

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.

This question is related to java date calendar converter

The answer is


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.


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.


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.


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.


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);
}

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);

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;
    }

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();
}

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/


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

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 calendar

Moment.js get day name from date HTML Input Type Date, Open Calendar by default Check if a given time lies between two times regardless of date Creating java date object from year,month,day How to set time to 24 hour format in Calendar How to get Month Name from Calendar? Get first date of current month in java Specify the date format in XMLGregorianCalendar Getting last day of the month in a given string date How to change TIMEZONE for a java.util.Calendar/Date

Examples related to converter

No converter found capable of converting from type to type How to convert datetime to integer in python Convert Int to String in Swift Concatenating elements in an array to a string Decimal to Hexadecimal Converter in Java Calendar date to yyyy-MM-dd format in java ffmpeg - Converting MOV files to MP4 Java: How to convert String[] to List or Set Convert xlsx to csv in Linux with command line How to convert string to long