3

I need to convert a 24 hour date format for a given string into milliseconds. But I get the same milliseconds for 00:10:00 and 12:10:00. This is my code sample; please assist me.

DateFormat formate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 

formate.parse("2013-10-31 12:10:00").getTime(); //  return 1383158400000

formate.parse("2013-10-31 00:10:00").getTime();  // return 1383158400000

I am using 24 hours format, but I get the same result for 2 different times. Where is the mistake? Please help me to find out the problem.

user2672165
  • 2,986
  • 19
  • 27
M.A.Murali
  • 9,988
  • 36
  • 105
  • 182

2 Answers2

9

You are using the 12-hour hh format; use the 24-hour HH (capitalized) format.

DateFormat formate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 

H Hour in day (0-23) Number 0

h Hour in am/pm (1-12) Number 12

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
0

java.time

Without AM/PM marker, the date-time parser considers the hour in 24-Hour format for which the symbol is H instead of h.

Changing that will fix your problem but the legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using them completely and switch to java.time, the modern date-time API*.

Demo using modern date-time API:

import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String args[]) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH).withZone(ZoneOffset.UTC);
        System.out.println(Instant.from(dtf.parse("2013-10-31 12:10:00")).toEpochMilli());
        System.out.println(Instant.from(dtf.parse("2013-10-31 00:10:00")).toEpochMilli());
    }
}

Output:

1383221400000
1383178200000

Learn more about the the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110