Question

I am trying to parse one string to a format yyyy-MM-dd and one to yyyy-MM-dd HH:mm:ss. I am using SimpleDateFormat.

I have used the same method successfully earlier, but now something is going wrong. I get the date in the standard format i.e. Tue Mar 05 00:00:00 GMT+05:30 2012 (for yyyy-MM-dd) and Mon Mar 05 13:01:35 GMT+05:30 2012 (for yyyy-MM-dd HH:mm:ss) where as I need them to be 2012-03-05 and 2012-03-05 13:01:35 repectively.

This is what I do :

Date today = new Date();
SimpleDateFormat tsdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
    today = tsdf.parse(tsdf.format(new Date()));
} catch(Exception e) {
    System.out.println("Error occurred"+ e.getMessage());
}

System.out.println(today);

AND

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
    // I recieve a string in this format here (refers to 5 march 2012).
    myDate = sdf.parse('2012-03-05');            
    System.out.println(myDate);
} catch(Exception e) {
    System.out.println("Error occurred "+ e.getMessage());
}
Was it helpful?

Solution

today = tsdf.parse(tsdf.format(new Date()));
System.out.println(today);

Looks to me like you expect, that the Date instance gets formatted. That is not the case. A Date instance represents a date that can be formatted "to" a string. It is a class that simply holds a long value (meaning something like "time in milliseconds").

This would give the expected result:

Date today = new Date();
String formattedDate = tsdf.format(today);
System.println(formattedDate);     // <- we print the string!!

OTHER TIPS

You're not outputting the string that is the result of the formatter, you're outputting the actual date object. That will always be the result of Date.toString(), which for the JDK you're using is the format you see. Don't turn the formatted String back into a date object, just print it out!

SimpleDateFormat tsdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
    String formattedDate = tsdf.format(new Date());
} catch(Exception e) {
    System.out.println("Error occurred"+ e.getMessage());
}

System.out.println(formattedDate);

You cannot apply a "format" to a java.util.Date object for later use. It's just a raw number of milliseconds and its toString method will always print the same representation. You have to convert it into a formatted string and use that string.

If you want format a Date instance, you don't must using parse method, you have to use format method as following:

    Date today = new Date();
    SimpleDateFormat tsdf = new SimpleDateFormat("yyyy-MM-dd");
    try
    {
        System.out.println(tsdf.format(today));
    }
    catch (Exception e)
    {
        System.out.println("Error occurred" + e.getMessage());
    }

parse method use for convert a string to date and format method for format a Date instance to string by specified format.

java.time

You are using old troublesome date-time classes now supplanted by the java.time classes.

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

LocalDate

For date-only values, use the LocalDate class. Your input value is in standard ISO 8601 format. The ISO 8601 formats are used by default in java.time classes for parsing and generating strings that represent the date-time values. So no need to specify a formatting pattern.

LocalDate localDate = LocalDate.parse( "2012-03-05" );

To generate such a string, call toString.

String output = localDate.toString();

LocalDateTime

For a string such as 2012-03-05 12:34:56 we have a problem. No offset-from-UTC or time zone is indicated. So it does not represent an actual moment on the timeline, but rather a rough idea about possible moments. This non-moment is represented in java.time by the LocalDateTime class.

Your string’s format is a variation on ISO 8601 while the canonical version has a T in the middle rather than a space. So one option is to replace the SPACE with a T.

LocalDateTime ldt = LocalDateTime.parse( "2012-03-05 12:34:56".replace( " " , "T" );

Or define a pattern.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyy-MM-dd hh:mm:ss" );
LocalDateTime ldt = LocalDateTime.parse( "2012-03-05 12:34:56" , formatter );

Avoid using such date-time formats lacking in offset or time zone info if indeed they are meant to represent actual moments on the timeline.

ZonedDateTime

To give that value meaning, to determine an actual moment on the timeline, we need to assign the time zone for which the date-time is intended.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ldt.atZone( zoneId );

Calling toString generates a String in a format that extends the ISO 8601 standard format by appending the name of the time zone in square brackets.

String output = zdt.toString(); // Yields: 2012-03-05T12:34:56-04:00[America/Montreal]

If you want to omit the T you could replace with a SPACE using String::replace method. Or use a formatter. If you really want a string as seen in the Question lacking any offset or time zone info (against my recommendation) use the same formatter shown above.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyy-MM-dd hh:mm:ss" );  // Not recommended as it lacks offset/zone info.
String output = zdt.format( formatter );  // Yields: 2012-03-05 12:34:56
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top