user7456985
user7456985

Reputation: 13

Date is getting changed while parsing

In the following code the date is getting changed while parsing: In particular the minutes are getting increased by 5 mins. Why is this happening?

String inputDate="2016-12-01T16:30:59.264448";             
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS");
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
java.util.Date parsedTimeStamp=null;

if(!inputDate.contains(".")){
     try {
           parsedTimeStamp = dateFormat1.parse(inputDate.replace("T", " "));
     } catch (ParseException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
     }
}else{
     try {
    parsedTimeStamp = dateFormat.parse(inputDate.replace("T", " "));

     } catch (ParseException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
     }
}
System.out.println("Date-->"+parsedTimeStamp);

Upvotes: 1

Views: 980

Answers (2)

Meno Hochschild
Meno Hochschild

Reputation: 44071

If you have a strong requirement to preserve microsecond precision in your input then you might consider the new class java.time.LocalDateTime introduced in Java-8 which can store up to nanoseconds. And your input does not contain any zone or offset information so LocalDateTime is the best choice as type. Example using just ONE formatter:

String input1 = "2016-12-01T16:30:59.264448";
String input2 = "2016-12-01T16:30:59";

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss[.SSSSSS]");

LocalDateTime ldt1 = LocalDateTime.parse(input1, dtf); // 2016-12-01T16:30:59.264448
LocalDateTime ldt2 = LocalDateTime.parse(input2, dtf); // 2016-12-01T16:30:59

You can also use following bridge to old Date-type (legacy-API):

java.util.Date d = java.util.Date.from(ldt1.atZone(ZoneId.systemDefault()).toInstant());

Upvotes: 1

Exception_al
Exception_al

Reputation: 1089

2 Things , If you look at the Documentation for SimpleDateFormat (Java 8 or 7), especially the part about "Date and Time Patterns", you notice

H Hour in day (0-23)
h Hour in am/pm (1-12)

So you should consider using the below for the

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

and those Milliseconds that you provide are converted to seconds / minutes and hence the result.

Upvotes: 2

Related Questions