How to parse a Date with TimeZone with and without colon [duplicate] - java

This question already has answers here:
DateTimeFormatter Accepting Multiple Dates and Converting to One (java.time library)
(4 answers)
How to parse dates in multiple formats using SimpleDateFormat
(13 answers)
Generic support for ISO 8601 format in Java 6
(2 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
The below code for date parse works fine for the date "2015-03-25T09:24:10.000+0530" :-
String time = "2015-03-25T09:24:10.000+0530";
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
LocalDateTime localDateTime = LocalDateTime.parse(time, timeFormatter);
System.out.println("localDateTime:"+localDateTime);
Also, the below code works fine for the date "2015-03-25T09:24:10.000+05:30"
String time = "2015-03-25T09:24:10.000+05:30";
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
LocalDateTime localDateTime = LocalDateTime.parse(time, timeFormatter);
System.out.println("localDateTime:"+localDateTime);
But Im trying to find a pattern which match either "2015-03-25T09:24:10.000+0530" or "2015-03-25T09:24:10.000+05:30". Is that possible without doing stuff like checking whether the input date has colon or not?
I felt adding 'X' towards ending of datePattern would help according to the doc but it didnt. https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.
Any suggestions?

Keep the optional patterns inside the square bracket.
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS[XXX][X]", Locale.ENGLISH);
Stream.of(
"2015-03-25T09:24:10.000+0530",
"2015-03-25T09:24:10.000+05:30"
).forEach(s -> System.out.println(OffsetDateTime.parse(s, dtf)));
}
}
Output:
2015-03-25T09:24:10+05:30
2015-03-25T09:24:10+05:30
Learn more about the modern date-time API from Trail: Date Time.

Interesting question. You can use parseBest.
String[] test = {"2015-03-25T09:24:10.000+0530" , "2015-03-25T09:24:10.000+05:30" };
for (String s : test) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS[Z][XXX]");
TemporalAccessor result = formatter.parseBest(s, ZonedDateTime::from, ZonedDateTime::from);
System.out.println(result);
}
This outputs
2015-03-25T09:24:10+05:30
2015-03-25T09:24:10+05:30

Related

Java: SimpleDateFormat not simplifying to specified pattern? [duplicate]

This question already has answers here:
display Java.util.Date in a specific format
(11 answers)
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
(11 answers)
convert java.util.Date to java.util.Date with different formating in JAVA [duplicate]
(1 answer)
SimpleDateFormat ignoring month when parsing
(4 answers)
Closed 2 years ago.
Tried converting string of yyyy-mm-dd, example 2013-12-30, to date object using SimpleDateFormat.parse("yyyy-mm-dd").
Expected output of 2013-12-30, received output of Mon Dec 30 00:00:00 EST 2013 object.
Tried finding out why SimpleDateFormat is returning a different format, but overwhelmed when trying to look through the java api. Asking for clarifications on what is going on and what would be a better approach.
Note: Stuck using java.utl.Date.
...
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateArray = new Date[rowCount];
try {
for(int index = 0; index < rowCount; index++){
dateArray[index] = simpleDateFormat.parse(fileArray[index][0]);
System.out.println(dateArray[index].toString());
}
} catch(ParseException err){
System.out.println("ERR: Data parse exception. Format is not correct.");
err.printStackTrace();
}
The pattern, mm stands for minute, not month. For month, you need to use MM.
Demo:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws ParseException {
String strDate = "2013-12-30";
SimpleDateFormat sdfISO8601 = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdfISO8601.parse(strDate);
System.out.println(date);
String strDateISO8601 = sdfISO8601.format(date);
System.out.println(strDateISO8601);
// Some other format
String strSomeOtherFormat = new SimpleDateFormat("EEEE MMM dd yyyy").format(date);
System.out.println(strSomeOtherFormat);
}
}
I also recommend you check Convert UTC String to UTC Date.
Note that the date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. I suggest you should stop using them completely and switch to the modern date-time API.
Using the modern date-time API:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String strDate = "2013-12-30";
LocalDate date = LocalDate.parse(strDate);
System.out.println(date);
String strDate8601 = date.toString();
System.out.println(strDate8601);
// Custom format
String customFormat = DateTimeFormatter.ofPattern("EEEE MMM dd uuuu").format(date);
System.out.println(customFormat);
}
}
Your date string is already in ISO 8601 format for date and therefore do not need to use any formatter to parse it when you use the modern date-time API.
Learn more about the modern date-time API at Trail: Date Time.
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.

How can I convert a String formatted in this way into a Date using Java? [duplicate]

This question already has answers here:
Parse CIM_DateTime with milliseconds to Java Date
(2 answers)
Closed 2 years ago.
Into a Java application I have this String representing a timestamp containing values like this: 2009-10-17 05:45:14.000
As you can see the string represents the year, the month, the day, the hour, the minute, the second and the millisencond.
I have to convert a String like this into a Date object (if possible bringing also the millisecond information, is it possible?)
How can I correctly implement it?
You can use SimpleDateFormat to parse a given string date according to a given pattern, it also supports milliseconds, like this:
SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date date=format.parse("2009-10-17 05:45:14.050");
Since Java 8, you should use the classes in the date-time API
Class LocalDateTime stores a date and a time up to nanosecond precision.
Here is a snippet showing how to parse a string into an instance of LocalDateTime
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class DateTime {
public static void main(String[] args) {
String str = "2009-10-17 05:45:14.000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(str, formatter);
}
}

What should be the format in SimpleDateFormat to print date like this - 01-JUN-20 08.55.27.577984000 AM UTC? [duplicate]

This question already has answers here:
How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?
(16 answers)
How to get the current date/time in Java [duplicate]
(28 answers)
How to format a ZonedDateTime to a String?
(3 answers)
Closed 2 years ago.
I want to print the current date in this format -
01-JUN-20 08.55.27.577984000 AM UTC. Tried lot of formats in SimpleDateformat but none is working. What is the right way to print like this?
SimpleDateFormat
You can use the following pattern:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class TimeFormatting {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy hh.mm.ss.SSS a Z");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String formatted = formatter.format(new Date(2015, 4, 4, 13, 7, 19)); //One example date
System.out.println(formatted);
}
}
This will give the output 04-05-15 11.07.19.000 AM +0000 where +0000 equals to UTC.
Explanation of the pattern dd-MM-yy hh.mm.ss.SSS a Z:
dd = the day
MM = the month
yy = the year
hh = the hour
mm = the minute
ss = the second
SSS = the millisecond. There does not exist a reference to nanoseconds in SimpleDateFormat (see this answer).
a = to show AM/PM
Z = to show the timezone
Additional information
Please note: SimpleDateFormat is deprecated. You should use DateTimeFormatter. One big advantage is that you can also have the nanoseconds (n).
One example:
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.ZoneOffset;
public class TimeFormatting {
public static void main(String[] args) {
ZonedDateTime time = ZonedDateTime.now(ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy hh.mm.ss.n a 'UTC'").withZone(ZoneOffset.UTC);
String timeDate = time.format(formatter);
System.out.println(timeDate);
}
}
Edit:
If you want to have UTC instead of +0000 with SimpleDateFormat you can use dd-MM-yy hh.mm.ss.SSS a zzz instead.

Unable to Convert String to localDate with custom pattern [duplicate]

This question already has answers here:
How to format LocalDate object to MM/dd/yyyy and have format persist
(4 answers)
Closed 2 years ago.
import java.util.*;
import java.lang.*;
import java.io.*;
import java.time.*;
import java.time.format.*;
import java.text.*;
public class ConvertStringToDate {
public static void main(String[] args)throws Exception {
String date = "2020-06-14";
DateTimeFormatter Stringformatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// convert String to LocalDate
LocalDate localDate = LocalDate.parse(date, Stringformatter);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
String formattedDate = localDate.format(formatter); // output here is as expected 14.06.2020
// facing issues when converting back to localDate with defined pattern,
LocalDate parsedDate = LocalDate.parse(formattedDate, formatter); // expected output is 14.06.2020 but getting a LocalDate formatted 2020-06-14
// System.out.println(parsedDate);
// System.out.println(parsedDate.getClass().getName());
}
}
Apologizes for my explanation early days with java. Basically i am trying to convert input string "2020-06-14" into a localDate with a custom pattern "dd.MM.yyyy" in the end trying to have a date object not a String. Is there an other way to achieve it.
A date has no format. Therefore when you write
//expected output is 14.06.2020 but getting a LocalDate formatted 2020-06-14
your expectation is simply wrong. The date is parsed according to the formatter but how the date represents the parsed values and how it chooses to display them afterwards no longer has any connection to the formatter.
The only way to get your format back is to write parsedDate.format(formatter) once again and you are back where you started, which is what formattedDate was already.

GET DateTime from String [duplicate]

This question already has answers here:
Parsing ISO-8601 DateTime with offset with colon in Java
(4 answers)
Closed 6 years ago.
I am developing a java sample in which date is in string like - 2016-07-19T16:54:03.000+05:30.
I want to convert it to DateTime object.How can I do it in java?
I have tried this code -
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS+Z").parseDateTime("2016-07-19T16:54:03.000+05:30")
It give java.lang.IllegalArgumentException: Invalid format: "2016-07-19T16:54:03.000+05:30" is malformed at "05:30" exception.
You need to use ZZ instead of just Z for the timezone information.
i.e.
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ").parseDateTime("2016-07-19T16:54:03.000+05:30")
Taken from the Javadoc:
The count of pattern letters determine the format.
Zone: 'Z' outputs offset without a colon, 'ZZ' outputs the offset with a colon, 'ZZZ' or more outputs the zone id.
You could use SimpleDateFormat:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
class Main {
public static void main(String[] args) {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date parsed = format.parse("2016-07-19T16:54:03.000+05:30");
System.out.println(parsed);
} catch (ParseException e){
e.printStackTrace();
}
}
}
Output:
Tue Jul 19 11:54:03 UTC 2016
Try it here!
You can try java.text.DateFormat
String DEFAULT_DATE_PARSE_PATTERN="dd.MM.yyyy";
DateFormat format = new SimpleDateFormat(DEFAULT_DATE_PARSE_PATTERN);
Date result = format.parse(your_value);

Categories