Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple question about java SimpleDateFormat

This will probably be a dumb question, but I don't understand the java date function. Here is some code:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
Date s = sdf.parse(var);
Calendar scal = java.util.GregorianCalendar.getInstance();
scal.setTime(s);   
Log.w("Time: ", Long.toString(s.getTime()));

If var = "10:00" I get "64800000".

If var = "11:00" I get "68400000".

If var = "12:00" I get "28800000".

If var = "13:00" I get "75600000".

If var = "14:00" I get "79200000".

If var = "00:00" I get "28800000".

What is up with 12:00? Why, when var=12:00 do I get the same result as when it's 00:00? All the other results seem correct. I obviously don't understand the java date function, but I can't seem to find any explanation for this anywhere. This is screwing up my time span calculator.

like image 570
kungfuafrican Avatar asked Jan 11 '11 16:01

kungfuafrican


People also ask

What is the use of SimpleDateFormat in Java?

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.

Why is SimpleDateFormat not thread-safe?

2.2. Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally. So SimpleDateFormat instances are not thread-safe, and we should use them carefully in concurrent environments.

Is SimpleDateFormat can be used in multithreading?

Java's SimpleDateFormat is not thread-safe, Use carefully in multi-threaded environments. SimpleDateFormat is used to format and parse dates in Java. You can create an instance of SimpleDateFormat with a date-time pattern like yyyy-MM-dd HH:mm:ss , and then use that instance to format and parse dates to/from string.

Is SimpleDateFormat case sensitive?

The formats are case-sensitive. Use yyyy for year, dd for day of month and MM for month. You need to read the javadoc of SimpleDateFormat more carefully, Take special care for lower-case and upper-case in the patterns.


1 Answers

If you want to use 24-hour time, you need to use the capital HH format:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); 
like image 102
GriffeyDog Avatar answered Oct 23 '22 13:10

GriffeyDog