Calendar date to yyyy-MM-dd format in java

JavaDateCalendarConverter

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

Solution 3 - Java

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.

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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.

Solution 7 - Java

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.

Solution 8 - Java

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

Solution 9 - Java

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/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSarika.SView Question on Stackoverflow
Solution 1 - JavaMadProgrammerView Answer on Stackoverflow
Solution 2 - JavaNiroshan AbayakoonView Answer on Stackoverflow
Solution 3 - JavaBasil BourqueView Answer on Stackoverflow
Solution 4 - JavaKV PrajapatiView Answer on Stackoverflow
Solution 5 - JavaPetrView Answer on Stackoverflow
Solution 6 - JavaElderMaelView Answer on Stackoverflow
Solution 7 - JavaDrewView Answer on Stackoverflow
Solution 8 - JavaUnnati SolankiView Answer on Stackoverflow
Solution 9 - JavaJavaLearnerView Answer on Stackoverflow