Java- milliseconds (SSS) not being parsed with SimpleDateFormat [duplicate] - java

This question already has answers here:
Java date is not preserving milliseconds in conversion with simple date format
(5 answers)
Closed 7 years ago.
Basically I'm attempting to parse date/time to Java, but having issues when trying to parse the milliseconds.
Example of data to be parsed: a[0] = 16/03/2015, a[1] = 10:00:18.120
I read in the two values and concatenate them.
Getting: dateTime = (java.lang.String) "16/03/2015 10:00:18.120"
As you can see the string has the milliseconds when i debug it. From here I parse it to SimpleDateFormat. It works- however the milliseconds are not displayed
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS", Locale.ENGLISH);
String dateTime;
dateTime= a[0]+" "+a[1];
Date d = df.parse(dateTime);
Current output: d = (java.util.Date) Mon Mar 16 10:00:18 GMT 2015
Thanks for your help.

Your code is fine, but not your interpretation of the result. As correctly mentioned in one comment, the method toString() of class java.util.Date does not output the millisecond part. But the millisecond part is still part of the state of your result object. Proof:
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS", Locale.ENGLISH);
String dateTime = "16/03/2015 10:00:18.120";
Date d = df.parse(dateTime);
System.out.println(d); // Mon Mar 16 10:00:18 CET 2015
System.out.println(d.getTime()); // 1426496418120
System.out.println("millisecond-part=" + (d.getTime() % 1000)); // millisecond-part=120
So all is fine. You can even format your result back to a string using the same (or another instance of SimpleDateFormat - maybe with different pattern, locale and timezone).
If java.util.Date was correctly implemented as value-type then the inventors of that class would have taken care of making the output of toString() representing the whole exact state of the object but it has not happened - another example why this class is broken.

Using DateFormat.format(Date date) function might meet your requirement
Date date = new Date();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS",Locale.ENGLISH);
String dateTime;
dateTime=df.format(date);
String[] a=dateTime.split(" ");
System.out.println(a[0]+" "+a[1]);

DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS",Locale.ENGLISH);
String dateTime;
dateTime= "03/16/2015"+" "+"10:00:18.120";
Date d = df.parse(dateTime);
System.out.println(df.format(d));

Try this:
String[] a = new String[]{"16/03/2015", "10:00:18.120"};
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS", Locale.ENGLISH);
String dateTime = a[0] + " " + a[1];
try {
Date d = df.parse(dateTime);
System.out.println(d.getTime());//Returns milliseconds
} catch (ParseException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
The result: 1426492818120

Related

Unparseable date with SimpleDateFormatter

I have a date that keeps giving me an error of
java.text.ParseException: Unparseable date: " 5 April 2017  "
All other dates (without word months) work fine
The code I am using is below:
VisitDate=VisitDate.trim();
if (VisitDate.matches(".*[a-z].*")){
SimpleDateFormat changeDate = new SimpleDateFormat("dd_MMM_yy", Locale.UK);
//Convert the string to a date
Date date = changeDate.parse(VisitDate);
//Reformat the date the way I like it
SimpleDateFormat dt1 = new SimpleDateFormat("dd_MM_yy");
//Convert back into a string
try {
VisitDate=dt1.format(date);
if(VisitDate==null){
SimpleDateFormat dt2 = new SimpleDateFormat("dd MM yy");
//Convert back into a string
VisitDate=dt2.format(date);
if(VisitDate==null){
SimpleDateFormat dt3 = new SimpleDateFormat("dd MMMM yy");
//Convert back into a string
VisitDate=dt3.format(date);
if(VisitDate==null){
SimpleDateFormat dt4 = new SimpleDateFormat("d_MMM_yy");
//Convert back into a string
VisitDate=dt4.format(date);
if(VisitDate==null){
SimpleDateFormat dt5 = new SimpleDateFormat("d_MMMM_yy");
//Convert back into a string
VisitDate=dt5.format(date);
if(VisitDate==null){
SimpleDateFormat dt6 = new SimpleDateFormat("dd_MMM_yy");
//Convert back into a string
VisitDate=dt6.format(date);
if(VisitDate==null){
SimpleDateFormat dt7 = new SimpleDateFormat("dd_MMM_yyyy");
//Convert back into a string
VisitDate=dt7.format(date);
if(VisitDate==null){
SimpleDateFormat dt8 = new SimpleDateFormat("dd_MMMM_yyyy");
//Convert back into a string
VisitDate=dt8.format(date);
if(VisitDate==null){
VisitDate=VisitDate.replaceAll("\\s", "");
SimpleDateFormat dt9 = new SimpleDateFormat("dd MMMM yyyy");
//Convert back into a string
VisitDate=dt9.format(date);
}
}
}
}
}
}
}
}
} catch (Exception e) {
Logger.error(e+"->No visit Date frmo here with the original date as: "+date);
}
}
Happy to read your expressed interest in the modern date and time classes, here’s just a snippet to get you started:
String visitDate = " 5 April 2017 ";
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("d MMMM uuuu", Locale.UK);
visitDate = visitDate.trim();
LocalDate date = LocalDate.parse(visitDate, parseFormatter);
// reformat to the string we like
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd_MM_uu");
visitDate = date.format(formatter);
The result is
05_04_17
I have spelled visitDate with a small v since the Java coding conventions recommend that variable names begin with a small letter.
The uu is subtle and probably something you can ignore. It’s a signed year where 0 equals 1 BC, -1 equals 2 BC and so forth. Assuming none of your dates are that old, you can use u and y interchangeably.
I believe that neither SimpleDateFormat.format() nor LocalDate.format() will ever return null, so all your null checks are superfluous.
Link for further reading: Oracle tutorial: Trail: Date Time
You only have one SimpleDateFormatter being used for parsing:
SimpleDateFormat changeDate = new SimpleDateFormat("dd_MMM_yy", Locale.UK);
//Convert the string to a date
Date date = changeDate.parse(VisitDate);
It is using the format dd_MMM_yy, however you are passing 4 digits for the year.
The rest of your SimpleDateFormatters are being used for formatting to a string, not parsing from a string. Only the first one will be called, since it will be able to produce a string given a valid date, and the following null checks will stop any other formatters from being used.
You have the input string to parse like this: " 5 April 2017 ". But you have no pattern match for this input
First please trim the space of input string
Second please change the format of your string or add another pattern to parse this string, because you have month April with 5 letter, but you have no pattern with MMMMM. Usually the month will be shorten to 3 letter like: April -> Apr, March -> Mar ...

Is there any way of converting time from "hh:mm:ss" format to "hh:mm AM/PM" format? [duplicate]

This question already has answers here:
Conversion from 12 hours time to 24 hours time in java
(17 answers)
Closed 6 years ago.
I am storing time in the database in this format: "hh:mm:ss" (example- 09:30:00) and then retrieving and trying to show it to users in this format: "hh:mm AM/PM" (example- 09:30 AM).
I'm using below code for converting it:
DateFormat currentTime = new SimpleDateFormat("hh:mm a");
String startTimeInSF = currentTime.format(startTime);
String endTimeInSF = currentTime.format(endTime);
where startTime and endTime is in hh:mm:ss format, but the above code is producing this error: java.lang.IllegalArgumentException: Bad class: class java.lang.String.
Please let me know how can I successfully convert the time from hh:mm:ss to hh:mm AM/PM?
I think you should parse your "hh:mm:ss" time into a Date Object, then use formatter to format it to "hh:mm a".
Like this :
DateFormat format1 = new SimpleDateFormat("hh:mm:ss");
try {
Date date = format1.parse("01:11:22");
SimpleDateFormat format2 = new SimpleDateFormat("hh:mm a");
String result = format2.format(date);
return result;
} catch (ParseException e) {
e.printStackTrace();
}
I believe you're looking for the parse(String source) method. The format() methods take in a Date object and output a String representation of the object. the parse methods take in a String object and converts it to a Date object.
To do what you want, you'll need to have a DateFormat with hh:mm:ss, convert the database String to a Date using parse, and then use your existing DateFormat and use format on the Date object to get the output String to display to your user.
http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html
You need to change your code something like this, format function will not work directly on String object that is root cause of your exception.
DateFormat inputFormatter1 = new SimpleDateFormat"HH:mm:ss");
Date date1 = inputFormatter1.parse("22:10:11");
DateFormat outputFormatter1 = new SimpleDateFormat("hh:mm a");
String output1 = outputFormatter1.format(date1); //
Out will be 10:10 pm

How to convert this Date string into a long? [duplicate]

This question already has answers here:
Parsing ISO 8601 date format like 2015-06-27T13:16:37.363Z in Java [duplicate]
(2 answers)
Closed 6 years ago.
I am having issues converting a String that has this format for date from the server into a long?
Example Date String - "2016-07-04T00:02:34.457Z" (Note this is a string)
I tried this below but needs try catch around gmt, when I add it and a not null around cmtDt - then I initialize cmtDt to 0 pre setting it on the bottom and it is always 0.
Calendar c = Calendar.getInstance();
TimeZone tz = c.getTimeZone();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
formatter.setTimeZone(tz);
Date gmt = formatter.parse(comment.getDateCommented());
cmtDt = gmt.getTime();
First, your input String includes milliseconds (and your format does not). Second, your input String includes a literal Z (which is presumably to indicate a UTC timezone). Finally, getting your system timezone and assigning it to the formatter isn't reliably going to be UTC. You need something like,
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'Z'");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date gmt = formatter.parse("2016-07-04T00:02:34.457Z");
long cmtDt = gmt.getTime();
System.out.println(cmtDt);
} catch (Exception e) {
e.printStackTrace();
}
Which I ran, and got
1467590554457
Your format string for the SimpleDateFormat needs to be:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
My test code that works is:
Calendar c = Calendar.getInstance();
TimeZone tz = c.getTimeZone();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
formatter.setTimeZone(tz);
Date gmt = formatter.parse("2016-07-04T00:02:34.457Z");
long cmtDt = gmt.getTime();
System.out.println("cmtDt = " + cmtDt);
The format in SDF needs to be fixed. The following will help you.
Calendar c = Calendar.getInstance();
TimeZone tz = c.getTimeZone();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
formatter.setTimeZone(tz);
Date gmt = formatter.parse("2016-07-04T00:02:34.457Z");
long cmtDt = gmt.getTime();
System.out.println(cmtDt);
Prints : 1467599640457

Java DateFormat conversion automatically increases hour by 1

I am trying to take date in string and its input format string and converting the date in output format. However after conversion into Date, the java code increases the number of hours by one. I am not able to understand what causes the bug.
My Code:
try {
DateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
DateFormat inputFormat = new SimpleDateFormat(format);
Date date = inputFormat.parse(parameterValue);
parameterValue = outputFormat.format(date);
return parameterValue;
} catch (ParseException ex) {
// take action
}
format string: ddMMMyyyy / hh:mm z
Input Date: 07DEC2015 / 10:02 GMT
Output Date: 07/12/2015 11:02:00
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
resolved it.
If you don't want to use timezone, in java 8 you can use LocalDate/LocalTime/LocalDateTime:
LocalDateTime localDateTimeInstance = LocalDateTime.parse(dateToBeConverted, DateTimeFormatter.ofPattern(formatOfDateToBeConverted));
return localDateTimeInstance.format("dd/MM/yyyy hh:mm:ss");
/*
Also check out ZoneDate, ZoneTime (for timezone)
Checkout - LocalDate, LocalTime
*/

Java how to make date from string [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 8 years ago.
how can i make Date data type from String in java?
input: String "2014/01/01 18:02:02" => output: Date 2014/01/01 18:02:02
You could use a DateFormat to parse and format (they're reciprocal functions) the String. Something like,
String str = "2014/01/01 18:02:02";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
Date d = df.parse(str);
System.out.println(df.format(d));
} catch (ParseException e) {
e.printStackTrace();
}
Output is (as requested)
2014/01/01 18:02:02
please use SimpleDateFormat to parse String To Date.
In there you can find suitable DateFormat to convert this String to Date.
you can try this
String dateString = "2014/01/01 18:02:02";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime StringAsDate = LocalDateTime.parse(dateString, formatter);
I would recommend using Time(java.time) API instead of java.util for your Date & Time needs as it is new and exclusively added to java for Date & Time operations.
You can use the following code snippet -
String dateString = "10-11-2014";
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date inputDate = dateFormat.parse(dateString);
You can try this too.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String dateInString = "2014/01/01 18:02:02";
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
It is a working and it is also suitable to you as it is not complicated. you will get this output:
Wed Jan 01 18:02:02 IST 2014
2014/01/01 18:02:02
For your date following code should work :-
String myString = "2014/01/01 18:02:02";
DateFormat myDateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
Date myDate = myDateFormat.parse(myString);
For more details, see the documentation for SimpleDateFormat. Just make sure you use capital "MM" for month and small "mm" for minute.

Categories