I have a problem with GregorianCalendar so if you please can help me out with it. First I'll give you my code:
private String changeClock(String day, String clock, int change) {
String time="";
DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm");
try {
Date d=df.parse(day+" "+clock);
GregorianCalendar g=new GregorianCalendar();
g.setTime(d);
g.add(GregorianCalendar.HOUR_OF_DAY, change);
time=g.get(GregorianCalendar.YEAR)+"-"
+(g.get(GregorianCalendar.MONTH)+1)+"-"
+g.get(GregorianCalendar.DAY_OF_MONTH)+" "
+g.get(GregorianCalendar.HOUR_OF_DAY)+":"
+g.get(GregorianCalendar.MINUTE);
} catch (Exception e) {
e.printStackTrace();
}
return time;
}
Let me explain what is happening. I have a GUI with + and - button. When someone press + it add one hour, or if - is pressed then take one hour.
Now example, time is 23:00 and I press +, it is everything ok and it jumps to 00:00 of the next day. Problems are on 12:00. If it is 12:00 and I press + it goes to 1:00 and that goes on and on. It doesn't move to the next day even after 2x12 hours or 21465x12 hours.
Moving backward is a little better if I can say so. When it is 00:00 and I press - it changes to yesterday 23:00 (also date changes). If I then press + it changes also one day forward (so to today in this case).
What have I done wrong or what more should I write to my code?
Thanks for your help guys.
Your date format is wrong...
You're using hh, which is a representation of the "Hour in am/pm (1-12)", so a time of 1pm is been converted to 1am instead.
You should be using HH which is a a representation of the "Hour in day (0-23)".
Either that, or you need supply a date/time format with the am/pm marker...
Using either DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm"); or DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm a");
Instead of relying on String date/time values, you should be passing in and back a Date object, leave the formatting for the display.
tl;dr
LocalDateTime.parse(
"2016-01-02 12:34:56".replace( " " , "T" )
)
Using java.time
The Answer by MadProgrammer is correct: Wrong code used in formatting pattern. But there is an even easier and better approach.
You are using troublesome old date-time classes now supplanted by the java.time classes.
Your input format in almost in standard ISO 8601 format. Just replace the SPACE in middle with a T.
String input = "2016-01-02 12:34:56".replace( " " , "T" );
The java.time classe use ISO 8601 formats by default. So need to specify a formatting pattern at all, so no formatting codes to get wrong.
LocalDateTime ldt = LocalDateTime.parse( input );
We parse as a LocalDateTime because the input lacks information about offset-from-UTC or time zone. If this value was meant for UTC, apply an offset to get an OffsetDateTime.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC );
If meant for some time zone, transform into a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ldt.atZone( z );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, 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 (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Related
I am trying to parse the String to date. String having date format as
"dd-MMM-yyyy Z" and String having value "12-DEC-2018 ET". Its giving the error
java.text.ParseException: Unparseable date: "12-DEC-2018 ET".
The same code is working for String having value "12-DEC-2018 IST".
below is the code snippet:
public static void main(String[] args) throws ParseException {
String dateInputIST ="12-DEC-2018 IST";
String dateInputET ="12-DEC-2018 ET";
SimpleDateFormat sdfmt1 = new SimpleDateFormat("dd-MMM-yyyy Z");
SimpleDateFormat sdfmt2= new SimpleDateFormat("dd/MM/yyyy");
Date dDate = sdfmt1.parse( dateInputIST );
String strOutput = sdfmt2.format( dDate );
System.out.println(strOutput);
Date etDate = sdfmt1.parse(dateInputET);
strOutput = sdfmt2.format(etDate);
System.out.println(strOutput);
}
Could someone please help. I needed to parse the time in any timezone.
Thanks,
Navin
Change
String dateInputET ="12-DEC-2018 ET";
to
String dateInputET ="12-DEC-2018 EDT";
'ET' is not a recognized time zone.
Pseudo-zones
ET, EST, and IST are not actually time zones. Those 2-4 letter pseudo-zones are not standardized and are not even unique! For example, IST can mean India Standard Time, Ireland Standard Time, Iceland Standard Time, and more.
Real time zone names take the format of Continent/Region such as Africa/Tunis.
Date & zone, separately
Date with time zone has no real meaning.
Handle the date as a LocalDate object.
String input = "12-DEC-2018"
DayeTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
Handle your desired time zone separately, as a ZoneId object.
ZoneId zNewYork = ZoneId.of( "America/New_York" ) ;
To combine, determine the first moment of the day.
ZonedDateTime zdtNewYork = ld.atStartOfDay( z ) ;
Generate text representing that moment in standard ISO 8601 format extended to append the name of the time zone in square brackets.
To see that same moment in UTC, extract a Instant.
Instant instant = zdtNewYork.toInstant() ;
Adjust into another zone.
ZonedDateTime zdtKolkata = instant.atZone( ZoneId.of( "Asia/Kolkata" ) ) ;
To focus on the date only, get a LocalDate for the day of that same moment when viewed through the lens of the wall-clock time used in India.
LocalDate ldKolkata = zdtKolkata.toLocalDate() ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
java.time
DateTimeFormatter dateZoneFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("dd-MMM-uuuu v")
.toFormatter(Locale.ENGLISH);
String dateInputIST ="12-DEC-2018 IST";
String dateInputET ="12-DEC-2018 ET";
TemporalAccessor parsed = dateZoneFormatter.parse(dateInputIST);
System.out.println("Date: " + LocalDate.from(parsed) + " Time zone: " + ZoneId.from(parsed));
parsed = dateZoneFormatter.parse(dateInputET);
System.out.println("Date: " + LocalDate.from(parsed) + " Time zone: " + ZoneId.from(parsed));
On my computer the output from this snippet was:
Date: 2018-12-12 Time zone: Atlantic/Reykjavik
Date: 2018-12-12 Time zone: America/New_York
Format pattern letter v is for the generic time-zone name, that is, the name that is the same all year regardless of summer time (DST), for example Eastern Time or short ET.
If you want to control the interpretation of ambiguous time zone abbreviations (of which there are a lot), you may use the two-arg appendGenericZoneText(TextStyle, Set<ZoneId>) where the second argument contains the preferred zones. Still better if there is a way for you to avoid relying on time zone abbreviations altogether since, as I said, they are very often ambiguous.
I am not sure what sense a date with a time zone makes, though.
As an additional point, always specify locale for your formatters so they will also work if the default locale is changed or one day your program runs in a JVM with a different default locale.
Avoid SimpleDateFormat and Date
I don’t think SimpleDateFormat will be able to parse your string. It’s just the same since that class is already long outdated and is renowned for being troublesome, so you should never want to use it anyway.
I have date and time on string type 20/03/2018, 18:20:44 Is it possible to change it to date format in java? I tried this code:
public static Date getDate(String dateString) {
DateFormat formatter = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("PST"));
try {
Date date = formatter.parse(dateString);
return date;
} catch (ParseException e) {
logger.error("error while parsing milliseconds to date" + dateString, e);
}
return null;
}
I get unable to parse exception and returned with null
You've used the wrong string replacements inside your simple date format, it should be dd/MM/yyyy, HH:mm:ss. Note the capitalisation of the HH as well, your time is in 24 hour format so it must be HH over hh
So with the applied changes your code will look like this:
public static Date getDate(String dateString) {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy, HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("PST"));
try {
return formatter.parse(dateString);
} catch (ParseException e) {
logger.error("error while parsing milliseconds to date" + dateString, e);
}
return null;
}
Read more on the various patterns available here, as an aside it is generally recommended to use the ISO 8601 format for dates, so yours would be yyyy-MM-ddTHH:mm:ss
You should use the same format with input string:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy, hh:mm:ss");
You did two mistakes :
mm represents minutes. MM represents months.
But You specify mm in the month part of the date format.
the coma character : , provided in the input has also to be present in the date format.
So with a String input in this form : "20/03/2018, 18:20:44", you should use this DateFormat :
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy, hh:mm:ss");
tl;dr
Your formatting pattern was incorrect, using the wrong case and omitting the comma.
Also, you are using troublesome classes supplanted years ago by java.time classes.
LocalDateTime.parse( // Create a `LocalDateTime` object as the input string lacks any time zone or offset-from-UTC.
"20/03/2018, 18:20:44" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu, HH:mm:ss" ) // Define a formatting pattern to match the input.
)
.atZone( // Assign a time zone to the `LocalDateTime` to create a `ZonedDateTime` object.
ZoneId.of( "America/Los_Angeles" ) // Specify time zone to be assigned. Always use proper zone names `continent/region`; never use 3-4 character pseudo-zones.
)
2018-03-20T18:20:44-07:00[America/Los_Angeles]
java.time
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Parse your string as a LocalDateTime since it lacks an indicator of time zone or offset-from-UTC.
String input = "20/03/2018, 18:20:44" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu, HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
ldt.toString(): 2018-03-20T18:20:44
Lacking a time zone or offset-from-UTC means that this does not represent a moment, is not a point on the timeline. Without the context of a zone/offset, this represents only a vague idea about potential moments along a range of 26-27 hours.
Apparently you are certain this input was actually meant to be in certain time zone. Apply a ZoneId to this LocalDateTime to get a ZonedDateTime object.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
Conversion
Best to avoid the troublesome legacy classes. But if you must produce a java.util.Date to inter-operate with old code not yet updated for java.time, you can convert. To convert back and forth, call new methods on the old classes.
A java.util.Date represents a point on the timeline in UTC, with a resolution of milliseconds. So its replacement in java.time is Instant. An Instant is also a point on the timeline in UTC, with a finer resolution of nanoseconds. To get to a Date, we need an Instant, which we can pull from our ZonedDateTime.
Instant instant = zdt.toInstant() ; // Same moment, same point on the timeline, different wall-clock time.
Now we can get the legacy class object, Date, by calling Date.from.
java.util.Date date = Date.from( instant ) ; // Do this only if you *must* work with `Date` class.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I am trying to convert IST to UTC epoch in Java
But instead of subtracting 5.30 hours from IST, it adds 5.30 in IST
public static long convertDateToEpochFormat(String date) {
Date convertedDate = null;
try {
LOGGER.info(date);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
LOGGER.info(date);
convertedDate = formatter.parse(date);
LOGGER.info(convertedDate);
} catch (ParseException e) {
e.printStackTrace();
}
return convertedDate.getTime() / 1000L;
}
The log statements I obtained is :
2017-01-01 00:00:00
2017-01-01 00:00:00
Sun Jan 01 05:30:00 IST 2017
It should ideally be Dec 31 18:30:00 because of UTC conversion.
Can anyone tell me whats wrong ?
tl;dr
Why does util.Date forwards the date instead of subtracting it?
Because India time is ahead of UTC, not behind.
Instant.parse(
"2017-01-01 00:00:00".replace( " " , "T" ) + "Z"
).atZone(
ZoneId.of( "Asia/Kolkata" )
).toString()
2017-01-01T05:30+05:30[Asia/Kolkata]
Using java.time
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
ISO 8601
Your input string is almost in standard ISO 8601 format. To comply fully, replace that SPACE in the middle with a T. The java.time classes use standard formats when parsing/generating strings. So no need to specify a formatting pattern.
String input = "2017-01-01 00:00:00".replace( " " , "T" ) ;
If that input is meant to represent a moment in UTC, append a Z, short for Zulu, means UTC.
String input = "2017-01-01 00:00:00".replace( " " , "T" ) + "Z" ; // Assuming this input was intended to be in UTC.
2017-01-01T00:00:00Z
When possible, just use the ISO 8601 formats in the first place when serializing date-time values to strings.
Instant
Parse that input string as an Instant, a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.parse( input ) ;
instant.toString(): 2017-01-01T00:00:00Z
ZonedDateTime
You seem to want this value adjusted into India time. Apply a ZoneId to get a ZonedDateTime.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2017-01-01T05:30+05:30[Asia/Kolkata]
See this code run live at IdeOne.com.
India time is ahead of UTC
Your Question expects the India time to go backwards, behind the UTC value. This makes no sense. India time is ahead of UTC, not behind UTC. The Americas have time zones behind UTC as they lay westward. East of the Prime Meridian in Greenwich are offsets ahead of UTC. In modern times, ISO 8601 and most other protocols mark such offsets with a plus sign: +05:30. Note that some old protocols did the opposite (used a negative sign).
Midnight UTC = 5:30 AM India
So midnight in UTC, 00:00:00 at the Prime Meridian, is simultaneously five-thirty in the morning in India.
So all three of these represent the same simultaneous moment, the same point in the timeline:
2017-01-01T00:00:00Z
2017-01-01T05:30+05:30[Asia/Kolkata]
2016-12-31T16:00-08:00[America/Los_Angeles]
Avoid count-from-epoch
Do not handle time as an integer count from epoch as you are doing by returning a long from your method as seen in the Question. In your Java code pass around date-time values using date-time objects, java.time objects specifically. When passing date-time values outside your Java code, serialize to strings using the practical ISO 8601 formats.
Relying on an integer count-from-epoch values is confusing, difficult to debug, impossible to read by humans, and will lead to frustration and errors (even worse: unobserved errors).
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
The answer by Basil Bourque is not only correct, it is also very informative. I have already upvoted it. I’ll try just a little bit of a different angle.
As I understand your question, your date-time string 2017-01-01 00:00:00 should be interpreted in IST, AKA Asia/Kolkata time, and you want to convert it to seconds (not milliseconds) since the epoch. And you are asking why you are getting an incorrect result.
I think the answer is rather banal: When the date-time string is in India time, you should not set UTC time on the formatter you use for parsing it. This is sure to get an incorrect result (if you were to format the date-time into UTC, you would do well in setting UTC as time zone on the formatter used for formatting, but this is a different story).
I agree with Basil Bourque that you should avoid the outdated classes Date and SimpleDateFormat. So here’s my suggestion (assuming you do need epoch seconds and cannot use an Instant as Basil Bourque recommends).
private static DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
public static long convertDateToEpochFormat(String date) {
return LocalDateTime.parse(date, parseFormatter)
.atZone(ZoneId.of("Asia/Kolkata"))
.toInstant()
.getEpochSecond();
}
This will convert your example string into an instant of 2016-12-31T18:30:00Z and return 1483209000. Please check for yourself that it is correct.
I have been assuming all the way that by IST you meant Indian Standard Time. Please be aware that three and four letter time zone abbreviations are ambiguous. For example, my JVM thinks that IST means Israel Standard Time. If you intended the same, please substitute Asia/Jerusalem for Asia/Kolkata. If you meant Irish Standard Time (another recognized/semi-official interpretation), please use Europe/Dublin. You will of course get different output in each case.
I wrote a java utility function to convert yyyy/mm/dd as follows
public static long gettimestamp(String dateString) {
SimpleDateFormat df = new SimpleDateFormat("yyyy/mm/dd");
Date date;
try {
date = df.parse(dateString);
} catch (java.text.ParseException e) {
return 0;
}
long epoch = date.getTime();
return (epoch / 1000);
}
On passing 2014/06/12 - it gives 1389465360 (=Jan 11, 2014) which is wrong. Am I passing format in wrong way ?
You should uppercase the M. Lowercase m stands for minutes, while uppercase stands for month. Here's the documentation.
tl;dr
LocalDate.parse("2014/06/12".replace("/" , "-"))
.atStartOfDay(ZoneId.of("America/Montreal"))
.toEpochSecond()
Details
The Answer by Cornelissen is correct, your formatting pattern is incorrect.
Time zone
You fail to consider time zone. Your goal is getting a count of the seconds since the epoch of the start of 1970. That involves a time-of-day, when the day starts. The start of day varies around the globe by zone. A new day dawns earlier in Paris France than Montréal Québec.
Avoid old date-time classes
Furthermore, you are using troublesome old legacy date-time classes now supplanted by the java.time classes.
Use java.time
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu/mm/dd" );
LocalDate ld = LocalDate.parse( "2014/06/12" , f );
Alternatively, you could transform your input String to comply with standard ISO 8601 format by replacing the slash character with hyphen character. The java.time classes use ISO 8601 formats by default when parsing/generating strings.
Adjust that LocalDate into a specific time zone intended by the context of your date. We get a ZonedDateTime object.
Let java.time determine the start time of the day. Do not hard-code 00:00:00. In some time zones anomalies such as Daylight Saving Time (DST) may result in a day starting at a time such as 01:00:00.
ZoneId z = ZoneId.of( "America/Montreal" ); // Or ZoneOffset.UTC if you meant UTC (GMT).
ZonedDateTime zdt = ld.atStartOfDay( z );
You may interrogate for the number of whole seconds since the epoch of 1970-01-01T00:00:00Z.
long secondsSinceEpoch = zdt.toEpochSecond();
1402545600
Avoid using count-from-epoch
By the way, I strongly recommend against tracking date-time values as a count-since-epoch. Hard to read, hard to debug, prone to errors, leads to ambiguity over different epochs used by different software systems (at least a couple dozen epochs have been used).
Case in point: Your expected value of 1389465360 makes no sense to me. Using ZoneOffset.UTC I get the start of that date as 1402531200. Your expected value results in a time-of-day of 18:36 on January 11, 2014 when interpreted as a count of whole seconds since start of 1970 in UTC.
System.out.println ( Instant.ofEpochSecond ( 1_389_465_360L ).toString () );
2014-01-11T18:36:00Z
About java.time
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 project, now in maintenance mode, 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 (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I'm really scratching my head on this one. I've been using SimpleDateFormats with no troubles for a while, but now, using a SimpleDateFormat to parse dates is (only sometimes) just plain wrong.
Specifically:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = sdf.parse("2009-08-19 12:00:00");
System.out.print(date.toString());
prints the string Wed Aug 19 00:00:00 EDT 2009. What the heck? - it doesn't even parse into the wrong date all the time!
Update: That fixed it beautifully. Wouldn't you know it, that was misused in a few other places as well. Gotta love debugging other people's code :)
I think you want to use the HH format, rather than 'hh' so that you are using hours between 00-23. 'hh' takes the format in 12 hour increments, and so it assumes it is in the AM.
So this
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2009-08-19 12:00:00");
System.out.print(date.toString());
Should print out
Wed Aug 19 12:00:00 EDT 2009
The hour should be specified as HH instead of hh. Check out the section on Date and Time patterns in http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html
You're printing out the toString() representation of the date, rather than the format's representation. You may also want to check the hour representation. H and h mean something different. H is for the 24 hour clock (0-23), h is for the 12 hour clock (1-12), (there is also k and K for 1-24 and 0-11 based times respectively)
You need to do something like:
//in reality obtain the date from elsewhere, e.g. new Date()
Date date = sdf.parse("2009-08-19 12:00:00");
//this format uses 12 hours for time
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//this format uses 24 hours for time
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.print(sdf.format(date));
System.out.print(sdf2.format(date));
tl;dr
LocalDateTime ldt = LocalDateTime.parse( "2009-08-19 12:00:00".replace( " " , "T" ) );
java.time
Other Answers are correct but use legacy date-time classes. Those troublesome old classes have been supplanted by the java.time classes.
Your input string is close to standard ISO 8601 format. Tweak by replacing the SPACE in the middle with a T. Then it can be parsed without specifying a formatting pattern. The java.time classes use ISO 8601 by default when parsing/generating Strings.
String input = "2009-08-19 12:00:00".replace( " " , "T" );
The input data has no info about offset-from-UTC or time zone. So we parse as a LocalDateTime.
LocalDateTime ldt = LocalDateTime.parse( input );
If by the context you know the intended offset, apply it. Perhaps it was intended for UTC (an offset of zero), where we can use the constant ZoneOffset.UTC.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC );
Or perhaps you know it was intended for a particular time zone. A time zone is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST).
ZonedDateTime zdt = ldt.atZone( ZoneId.of( "America/Montreal" ) );
About java.time
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 project, now in maintenance mode, 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 (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.