I am struggling with this ..
I have an input string - like this: 2021-10-13 11:33:16.000-04
Using Java.
I need to get a Date object from it.
which formatting pattern can I use ?
I try with these
SimpleDateFormat inFormatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss.SSS'-'ZZ");
and
SimpleDateFormat inFormatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss.SSSZZ");
and I keep getting
java.text.ParseException: Unparseable date: "2021-10-13 11:33:16.000-04"
at java.base/java.text.DateFormat.parse(DateFormat.java:396)
at com.dima.tests.DatesConversions.main(DatesConversions.java:24)
Please, help !!
Don't use Date as it is outdated. Use the classes in the java.time
OffsetDateTime odt = OffsetDateTime.parse(str,
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSX"));
System.out.println(odt);
Prints
2021-10-13T11:33:16-04:00
java.time
Even though you need to give an old-fashionede Date object to a legacy API beyond your control, I still recommend that you use java.time, the modern Java date and time API, in your own code. The final conversion to Date is pretty straight-forward.
I’d use this formatter for maximum reuse of existing formatters:
private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendOffset("+HHmm", "+00")
.toFormatter(Locale.ROOT);
Then we parse and convert like this:
String input = "2021-10-13 11:33:16.000-04";
OffsetDateTime dateTime = OffsetDateTime.parse(input, PARSER);
System.out.println(dateTime);
Instant i = dateTime.toInstant();
Date oldfashionedDate = Date.from(i);
System.out.println(oldfashionedDate);
Output in my time zone, Europe/Copenhagen:
2021-10-13T11:33:16-04:00
Wed Oct 13 17:33:16 CEST 2021
Denmark is at offset +02:00 at this time of year, so 6 hours ahead of the UTC offset -04 from your string. Therefore Date.toString() confusingly prints a clock hour that is 6 hours ahead of the original time of day.
Note: if your forward service accepts anything else than an old-fashioned Date, you should not be using that class. For example, if a String is required, the OffsetDateTime that we got can be formatted into a new string using a second DateTimeFormatter (or in lucky cases, its toString method).
What went wrong in your code?
First, a UTC offset can have positive or negative sign. Instead of -04 you could have had for example +09. Formatters are designed for to take the sign, + or -, as part of the offset. Therefore hardcoding the minus sign as a literal, as in your first attempt, is bound to fail. In your second attempt, yyyy-MM-dd HH:mm:ss.SSSZZ, you are already closer. However, ZZ is for an offset with sign and four digits (like +0530 or -0400; hour and minute), so does not work for a two-digit offset like -04. Your SimpleDateFormat expected more digits where your string ended and therefore threw the exception that you saw.
Link
Oracle tutorial: Date Time explaining how to use java.time.
Since you are using ISO 8601 time zone timezone, you have the use the below pattern.
SimpleDateFormat inFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSX");
And then, to get the date:
Date date = inFormatter.parse("2021-10-13 11:33:16.000-04");
Always check the documentation.
Related
I want to convert the date in string to date object being the string "10h 57m 20s October 13 2020". How can be done? may replace firstly the h, m and s to get the format "10:57:20 October 13 2020"? As well, I tried the last format "10:57:20 October 13 2020" to get the date with DateTimeFormat and DateTimeFormatterBuilder() but is does not work with the month or it works but the hour coverts to 00:00:00.
Thanks
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work. Like Joop Eggen already wrote, put the letters that are part of your format in single quotes in the format pattern string:
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("H'h' m'm' s's' MMMM d y", Locale.ENGLISH);
This will allow you to parse like this:
String dateInString = "10h 57m 20s October 13 2020";
LocalDateTime dateTime = LocalDateTime.parse(dateInString, FORMATTER);
System.out.println(dateTime);
Output:
2020-10-13T10:57:20
You shouldn’t take any interest in the old-fashioned Date class. However, sometimes we need to pass a Date to a legacy API not yet upgraded to java.time. The conversion requires that we know the time zone assumed for the parsed date and time. For example:
ZoneId zone = ZoneId.of("America/Tegucigalpa");
Instant i = dateTime.atZone(zone).toInstant();
Date oldfashionedDate = Date.from(i);
System.out.println(oldfashionedDate);
Example output:
Tue Oct 13 10:57:20 CST 2020
Tutorial link
Oracle tutorial: Date Time explaining how to use java.time.
You can place fixed letters in apostrophes.
"HH'h' mm'm' ss's' MMMM dd yyyy"
Furthermore hh is the 12 hour format to be combined wiht a AM/PM.
HH is the 24 hour format.
Also the locale must be correct, maybe explicitly set. Here English.
I'm working on an app where users can timestamp themselves IN or OUT from their workplace. At the moment I'm trying to get the localization of the timestamps done. For example when I make a timestamp in UTC +02:00 at 08:00 02.01.2020, it works correctly and shows the time as 08:00 and right date as well. But when I change to UTC +01:00 in my phone settings, and do the same timestamp, the time becomes 07:00 and date becomes 01.01.2020.
The code I have so far for "parsing" the time looks like this:
String formattedTime = "";
String datetime2 = "1970-01-01T" + returntime;
Log.v("DATE", datetime2);
OffsetDateTime odt2 = OffsetDateTime.parse(datetime2);
Date date2 = Date.from(odt2.toInstant());
SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm",Locale.getDefault());
formattedTime = sdf2.format(date2);
Log.v("FORMTIME", formattedTime);
I'm using a similar code snippet for "parsing" the date as well.
The output for the two logs (when in UTC +01:00):
V/DATE: 1970-01-01T15:00:00+02:00
V/FORMTIME: 14:00 //SHOULD BE 15:00
V/DATE: 1970-01-01T08:00:00+02:00
V/FORMTIME: 07:00 //SHOULD BE 08:00
V/DATE: 1970-01-01T08:00:00+02:00
V/FORMTIME: 07:00 //SHOULD BE 08:00
It seems like the change in UTC from +02:00 to +01:00 reduce the time and date also with 1...
So is it wrong to use the OffsetDateTime class and "toInstant" (Instant class) for what I'm trying to achieve? What would be the right solution?
OffsetTime
I don’t understand what that offset of +02:00 in your string signifies. In particular it confuses me what you want to do when the offset changes. In any case java.time, the modern Java date and time API, parses and formats your time pretty easily. Let’s first define the formatter that describes your desired output format:
private static final DateTimeFormatter timeFormatter
= DateTimeFormatter.ofPattern("HH:mm");
With this in place you may do:
String returntime = "15:00:00+02:00";
OffsetTime time = OffsetTime.parse(returntime);
String formattedTime = time.format(timeFormatter);
System.out.println(formattedTime);
Output:
15:00
The offset is parsed, but is not used for anything. The output time will always be the same as the time in the string.
I take it that the date 1970-01-01 that you used in your code is arbitrary and without significance. The OffsetTime that I am using hasn’t got a date, so saves us from choosing a date for processing the time.
Word use: There isn’t any localization going on here. Localization is when for an American audience you print 3:00 PM instead of 15:00, for example.
EDIT:
If your string contains a date too, OffsetDateTime is the right class to use, and again we need no explicit formatter for parsing (only for formatting). Your code in the comment is fine (except that you had accidentally reversed the order of day, month and year in the string).
String returnDate1 = "2020-12-05T00:00+02:00";
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
OffsetDateTime dateTime = OffsetDateTime.parse(returnDate1);
String formattedDate = dateTime.format(dateFormatter);
System.out.println(formattedDate);
05-12-2020
What went wrong in your code?
It seems you were over-complicating things. In particular you were mixing old and modern date-time classes. The old ones, Date and SimpleDateFormat, are poorly and confusingly designed, which no doubt contributed to your unexpected results. And when mixing, you are going to need conversions that are not really needed for your job, again just making your code more complicated than needed.
Your sdf2 was using your default time zone for printing the time. You had got offset +02:00 in the string, so when you set the phone to UTC+01:00, a conversion takes place. When the time is 08:00 at offset +02:00, it is only 07:00 at offset +01:00. So this was the result you got. This in turn means that if the user’s time zone was at offset +01:00 on 1970-01-01, then you were getting the correct times for that time zone.
I have been parsing dates in the below formats. I maintain an array of these formats and parse every date string in all these formats.
The code I used was -
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
simpleDateFormat.setTimeZone(timeZone); //timeZone is a java.util.TimeZone object
Date date = simpleDateFormat.parse(dateString);
Now I want to parse yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX format as well but using SimpleDateFormat the 6 digit microseconds are not considered. So I looked into java.time package.
To parse yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX formats I will be needing OffsetDateTime class and for other formats, I need ZonedDateTime class. The format will be set in DateTimeFormatter class.
Is there a way to use a single class like SimpleDateFormat to pass all the formats?
Since your Java 8 doesn’t behave as would be reasonably expected, I suggest that a workaround is trying to parse without zone first. If a zone or an offset is parsed from the string, this will be used. If the parsing without zone fails, try with a zone. The following method does that:
private static void parseAndPrint(String formatPattern, String dateTimeString) {
// Try parsing without zone first
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatPattern);
Instant parsedInstant;
try {
parsedInstant = formatter.parse(dateTimeString, Instant::from);
} catch (DateTimeParseException dtpe) {
// Try parsing with zone
ZoneId defaultZone = ZoneId.of("Asia/Calcutta");
formatter = formatter.withZone(defaultZone);
parsedInstant = formatter.parse(dateTimeString, Instant::from);
}
System.out.println("Parsed instant: " + parsedInstant);
}
Let’s try it:
parseAndPrint("yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX", "2018-10-22T02:17:58.717853Z");
parseAndPrint("yyyy-MM-dd'T'HH:mm:ss.SSSSSS", "2018-10-22T02:17:58.717853");
parseAndPrint("EEE MMM d HH:mm:ss zzz yyyy", "Mon Oct 22 02:17:58 CEST 2018");
Output on Java 8 is:
Parsed instant: 2018-10-22T02:17:58.717853Z
Parsed instant: 2018-10-21T20:47:58.717853Z
Parsed instant: 2018-10-22T00:17:58Z
The first example has an offset in the string and the last a time zone abbreviation in the string, and in both cases are these respected: the instant printed has adjusted the time into UTC (since an Instant always prints in UTC, its toString method makes sure). The middle example has got neither offset nor time zone in the string, so uses the default time zone of Asia/Calcutta specified in the method.
That said, parsing a three or four letter time zone abbreviation like CEST is a dangerous and discouraged practice since the abbreviations are often ambiguous. I included the example for demonstration only.
Is there a way to use a single class…?
I have used Instant for all cases, so yes there is a way to use just one class. The limitation is that you do not know afterward whether any time zone or offset was in the string nor what it was. You didn’t know when you were using SimpleDateFormat and Date either, so I figured it was OK?
A bug in Java 8?
The results from your demonstration on REX tester are disappointing and wrong and do not agree with the results I got on Java 11. It seems to me that you have been hit by a bug in Java 8, possibly this one: Parsing with DateTimeFormatter.withZone does not behave as described in javadocs.
I'm trying to convert my String in Date + Timezone.
I get my String from a DateTime Variable (here: xyz).
My code:
String abc = xyz.toString("yyyy-MM-ddZZ");
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-ddXXX");
java.util.Date date = sdf.parse(abc);
System.out.println("Date: " + sdf.format(date));
Error:
Invalid format: "2017-01-03+01:00" is malformed at "+01:00"
If I try SimpleDateFormat("yyyy-MM-dd"); it works but without the Timezone ("+01:00")
The input has a date - year, month, day - and an offset - the difference from UTC - but to build a java.util.Date, you also need the time: hour, minutes, seconds, fraction of seconds.
SimpleDateFormat is terrible because it does some "magic", setting the missing fields to default values. Another problem is that the X pattern doesn't work for all Java versions, and the documentation sucks.
You can use the new Java 8 classes, as explained. With them, you can parse the input, choose the default values to be used for the time fields and convert to java.util.Date, if that's what you need:
DateTimeFormatter fmt = new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_OFFSET_DATE)
// set hour to midnight
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0).toFormatter();
OffsetDateTime odt = OffsetDateTime.parse("2017-01-03+01:00", fmt); // 2017-01-03T00:00+01:00
The OffsetDateTime will have the time set to midnight, but you can change it to whatever values you need, while with SimpleDateFormat it's not possible, because it uses internal default values and you can't control it.
And the date and offset were correctly set to the values in the input string. You can then convert to java.util.Date if you want:
Date date = Date.from(odt.toInstant());
You can also get the individual "pieces" of the date if you want:
// get just the date
LocalDate localDate = odt.toLocalDate(); // 2017-01-03
// get just the offset
ZoneOffset offset = odt.getOffset(); // +01:00
PS: the offset +01:00 is not the same thing as a timezone. See the difference here
String abc = "2017-01-03+01:00";
TemporalAccessor parsed = DateTimeFormatter.ISO_OFFSET_DATE.parse(abc);
LocalDate date = LocalDate.from(parsed);
ZoneOffset offset = ZoneOffset.from(parsed);
System.out.println("Date: " + date + "; offset: " + offset + '.');
This prints:
Date: 2017-01-03; offset: +01:00.
I am using java.time, the modern Java date and time API, and recommend you do the same. The Date class is long outdated (sorry, no pun intended) and SimpleDateFormat in particular notoriously troublesome. Don’t use them. The modern API is so much nicer to work with. Only if you need a java.util.Date and/or a java.util.TimeZone for a legacy API that you cannot change, convert like this:
Date oldfashionedDate = Date.from(date.atStartOfDay(offset).toInstant());
TimeZone oldfashionedTimeZone = TimeZone.getTimeZone(offset);
System.out.println("Old-fashioned date: " + oldfashionedDate
+ "; old-fashioned time-zone: " + oldfashionedTimeZone.getDisplayName() + '.');
On my computer this prints:
Old-fashioned date: Tue Jan 03 00:00:00 CET 2017; old-fashioned time-zone: GMT+01:00.
I happen to be in a time zone that agrees with your offset from UTC, so it’s fairly obvious that the conversion has given the correct result. In other time zones the output will be more confusing because Date.toString() uses the JVM’s time zone setting for generating the string, but the Date will still be correct.
A date with a time zone? Neither a LocalDate nor a Date can hold a time zone in them, so you need to have the offset information separately. Interestingly your string seems to follow a “ISO-8601-like” format for an offset date that is even represented by a built-in formatter that has ISO in its name. If Java had contained an OffsetDate or a ZonedDate class, I would have expected such a class to parse your string into just one object and even without an explicit formatter. Unfortunately no such class exists, not even in the ThreeTen-Extra project, as far as I can tell at a glance.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
ThreeTen Extra, more classes developed along with java.time.
EDIT: See my updated code run live on ideone.
"2017-01-03+01:00"
I thought it a similar ISO 8601 format date string, but actually not ISO 8601. Thanks #Meno Hochschild and #Basil Bourque's indication.
It is so luck that this method works for such format's string: javax.xml.bind.DatatypeConverter.parseDateTime, it will return a Calendar:
System.out.println(DatatypeConverter.parseDate("2017-01-03+01:00").getTime());
Output:
Tue Jan 03 07:00:00 CST 2017
From the method javadoc:
public static Calendar parseDate(String lexicalXSDDate)
Converts the string argument into a Calendar value.
Parameters: lexicalXSDDate - A string containing lexical
representation of xsd:Date.
Returns: A Calendar value represented by
the string argument.
Throws: IllegalArgumentException - if string
parameter does not conform to lexical value space defined in XML
Schema Part 2: Datatypes for xsd:Date.
I have date 2015-12-25 23:59:59 in the form of epoch milliseconds 1451087999000, And I want the date part only i.e. 2015/12/25, how do I do that efficiently might be with the JODA time library which is nowdays standard for dealing with Date time in java.
I have this code which works in most the case but when time is like 23:59:59 it gives me the next date (as in my case it gives 2015-12-26 with input of 2015-12-25 23:59:59)-
String dateInMilliSeconds = "1451087999000";
String dateInYYYYMMDDFormat = DateHelper.convertDateFormat(new Date(Long.valueOf(dateInMilliSeconds)),DateHelper.yyyy_MM_dd);
DateHelper.convertDateFormat() -
public static final String yyyy_MM_dd = "yyyy-MM-dd";
public static String convertDateFormat( Date date, String outputFormat )
{
String returnDate = "";
if( null != date )
{
SimpleDateFormat formatter = new SimpleDateFormat(outputFormat);
returnDate = formatter.format(date);
}
return returnDate;
}
You can use localDate from java 8
LocalDate date = Instant.ofEpochMilli(dateInMilliSeconds).atZone(ZoneId.of(timeZone)).toLocalDate();
I should like to make two points:
Time zone is crucial.
Skip the outdated classes Date and SimpleDateFormat.
My suggestion is:
String dateInMilliSeconds = "1451087999000";
LocalDate date = Instant.ofEpochMilli(Long.parseLong(dateInMilliSeconds))
.atOffset(ZoneOffset.UTC)
.toLocalDate();
System.out.println(date);
This prints
2015-12-25
Please note that you get your desired output format for free: LocalDate.toString() produces it. If you want to be able to produce different output formats, use a DateTimeFormatter.
Time zone
Your millisecond value isn’t just equal to 2015-12-25 23:59:59. It is equal to this date and time in UTC, so you need to make sure that your conversion uses this time zone offset. When I run your code from the question on my computer, I incorrectly get 2015-12-26 because my computer is in the Europe/Copenhagen time zone.
JSR-310 AKA java.time
Joda-Time was the widely acknowledged better alternative to the original date and time API from Java 1 that many considered poor and troublesome. The Joda-Time project is now finished because the modern Java date and time API known as JSR-310 or java.time came out three and a half years ago, so they recommend we use this instead. So my code does.
The timestamp 1451087999000 is 2015-12-25 23:59:59 in UTC. In your code, you're not specifying the timezone when you format it with a SimpleDateFormat, so it's formatted in your local timezone.
With Joda Time:
String dateInMilliSeconds = "1451087999000";
LocalDate date = new LocalDate(Long.parseLong(dateInMilliSeconds), DateTimeZone.UTC);
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
String result = formatter.print(date);