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);
Related
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
This question already has answers here:
parsing date/time to localtimezone
(2 answers)
How to Parse Date from GMT TimeZone to IST TimeZone and Vice Versa in android
(4 answers)
SimpleDateFormat returns wrong time zone during parse
(2 answers)
Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST
(9 answers)
Closed 2 years ago.
I have a String which represents a Date in the UTC timezone (because my database uses UTC). I want to convert this String into a date with SimpleDateFormat. The problem is that converts it into a Date in the CEST timezone without adding the 2 hour separating UTC and CEST. Here is the code:
//This is a date in UTC
String text = "2020-09-24T09:45:22.806Z";
//Here I define the correct format (The final Z means that it's UTC)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
//Then I parse it
Date date = sdf.parse(text);
//Then I print it
System.out.println(date);
The result of the print is
Thu Sep 24 09:45:22 CEST 2020
Why CEST? I would like it to remain UTC, but if it has to become CEST at least add the 2 hours
You should setTimeZone() to your DateFormat like
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws ParseException {
//This is a date in UTC
String text = "2020-09-24T09:45:22.806Z";
//Here I define the correct format (The final Z means that it's UTC)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
//Then I parse it
Date date = sdf.parse(text);
//Then I print it
System.out.println(date);
}
}
I also replaced 'Z' to X following the documentation
While validating the given string text is of Hmm format getting this error
java.text.ParseException: Unparseable date: "1637"
but this is working for text "747".
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Validation{
public void validateDateFormat(String format,String text){
SimpleDateFormat sdfrmt = new SimpleDateFormat(format);
sdfrmt.setLenient(false);
Date testDate = null;
try {
testDate = sdfrmt.parse(text);
} catch (ParseException e) {
System.out.println("dateFormat Exception :");
e.printStackTrace();
}
}
public static void main(String []args){
Validation val = new Validation();
val.validateDateFormat("Hmm","747"); //working
val.validateDateFormat("Hmm","1637");//not working
}
}
This is for validating the given columns from the uploaded file.So wrote this to be dynamic based on the format written in the config for each column.
Well, it should work.
But you should use the newer Java Date and Time API (JSR 310) available in the java.time package.
If you then replace Date with LocalTime, SimpleDateFormat with DateTimeFormatter (using the ofPattern factory method) and ParseException with DateTimeParseException, it'll work.
This is happening because the SimpleDateFormat is unable to parse the given date using the format you have given.
Let's understand - your format is Hmm and you have given the date as 747 then, of course during parsing, the first letter 7 of the date is mapped to the first letter "H" of the format i.e. hours and 47 is mapped to mm i.e. minutes and hence it is able to convert correctly but for the next date 1637 it is failing because it does not know which letter to assign to H.
Here are some options you can try to make it more generic, choose format such as HHmm and always give the date of length 4, for e.g. for 747 enter the input as 0747 and it should work.
Or choose a format that is more clear for the parser to map for e.g. you can choose the format as H:mm and give the inputs as 7:47 or 16:37 since there is a delimiter : between hours and minutes, the parser will be able to parse all types of time irrespective of the length of the given input 3 or 4.
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 String date into java.util.Date in the dd/MM/yyyy format [duplicate]
(1 answer)
return date type with format in java [duplicate]
(1 answer)
Calendar date to yyyy-MM-dd format in java
(11 answers)
Closed 3 years ago.
I have a requirement to convert String to Date (in dd-MM-yyyy format). But dateformat.parse gives the format with seconds. I need to convert the String date to Date in the same format as mentioned above.
The class Date will always contain both date a nd time information, since it represents an instant in time.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ParsingDate {
public static void main(String[] args) {
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date d;
try {
d = fmt.parse("04-12-2019");
System.out.println(d); // Wed Dec 04 00:00:00 CET 2019
} catch (ParseException e) {
e.printStackTrace();
}
}
}
As you can see, hours, minutes, seconds and millis get all set to 0.
If you later want to output the date in string format, you need to use the DateFormat#format(Date) method:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ParsingDate {
public static void main(String[] args) {
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date d = new Date();
System.out.println(d); // Wed Dec 04 11:24:35 CET 2019
System.out.println(fmt.format(d)); // 04-12-2019
}
}
If you'd rather store only date information, you could use the java.time package and make use of LocalDate.
LocalDate stores only date information, since it does not represent an instant, rather a triple of year, month and date.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class ParsingLocalDate {
public static void main(String[] args) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate d = LocalDate.parse("04-12-2019", fmt);
System.out.println(d); // 2019-12-04
}
}
If you do not need to use time of day or time zone, you can parse it by LocalDate.
String str = "01-01-2000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate date = LocalDate.parse(str, formatter);
Note that for day and time people most of the time would want a ZonedDateTime rather than a LocalDateTime. The name is counter-intuitive; the Local in both LocalDate and LocalDateTime means any locality in general rather than a specific time zone.
In most programming languages, date/time types are simply containers for the amount of time which has passed from a given point in time. They don’t have a format.
In the case of Java (AFAIR), time is measured in milliseconds since the Unix Epoch.
Since it's 2019, there is no excuse not to making use of the java.time APIs (or the ThreeTen backport) and you should avoid using the, now effectively deprecated, older APIs
Parse String to LocalDate
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate = LocalDate.parse("08-03-1972", inputFormatter);
Format LocalDate to desired format
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd EEE MMM yyyy");
String value = localDate.format(outputFormatter);
System.out.println(value);
which outputs
08 Wed. Mar. 1972
This question already has answers here:
Difference between java HH:mm and hh:mm on SimpleDateFormat
(5 answers)
Comparing time is incorrect when picking 12:00
(3 answers)
Closed 4 years ago.
I have having an issue converting dates in a json file to a timestamp. When the hour = 12, the timestamp being returned is incorrect.
Java version 1.8.0_171
Using the code snippet below, I expect the output to be
2017-07-19 07:43:42.0
2017-07-18 08:43:42.0
2017-07-19 09:43:42.0
Instead, I get
2017-07-19 07:43:42.0
2017-07-18 20:43:42.0
2017-07-19 09:43:42.0
I have tried on 2 machines, and had a co-worker run it, same results
Can anyone see what the issue is; I am probably staring at it
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;
public class TimestampTest {
public static void main(String[] args) {
String input = "2017-07-19T11:43:42.000+0000";
System.out.println(stringToTimestamp(input));
input = "2017-07-19T12:43:42.000+0000";
System.out.println(stringToTimestamp(input));
input = "2017-07-19T13:43:42.000+0000";
System.out.println(stringToTimestamp(input));
}
private static Timestamp stringToTimestamp(String input) {
try {
if(StringUtils.isBlank(input)) {
return null;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ",
Locale.getDefault());
java.util.Date parsedDate = dateFormat.parse(input);
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
return timestamp;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Aside from the fact you shouldn't be using Date or SimpleDateFormat any more, your error is because you are using hh instead of HH
h -> Hour in am/pm (1-12)
H -> Hour in day (0-23)
Consider using LocalDateTime in your case.
That happens because you are using SimpleDateFormat which is by default lenient. If you turn leniency off by setting setLenient(false):
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ", Locale.getDefault());
dateFormat.setLenient(false);
You will get an exception saying:
java.text.ParseException: Unparseable date: "2017-07-19T13:43:42.000+0000"
The root cause here is that you are submitting 13 for hours which requires HH pattern instead of hh. Because of leniency your code silently fixes the date instead of throwing an exception.
H Hour in day (0-23)
h Hour in am/pm (1-12)