I have searched online but couldn't really find the way to do it as I hope.
My data look like "20201005114527", "20201002173838" .......
and would like to convert them into LocalDateTime.
It will be converted into json again afterwards.
#JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "xxx/xxx")
private LocalDateTime xxxxxDate;
But I'm just confused of converting those "number-only strings" into LocalDateTime.
Use the format mask yyyyMMddHHmmss?
#JsonFormat(pattern = "yyyyMMddHHmmss")
private LocalDateTime xxxxxDate;
Parsing a date-time string containing only digits isn’t any different from parsing a date-time string in any other format.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss");
String numberOnlyString = "20201005114527";
LocalDateTime xxxxxDate = LocalDateTime.parse(numberOnlyString, formatter);
System.out.println(xxxxxDate);
Output:
2020-10-05T11:45:27
Related
I'm querying database and getting date in this format "01-SEP-22"
I want to convert this date into this format "yyyy-MM-dd" in Java. Is there any way I can do this.
java.time
I recommend that you use java.time, the modern Java date and time API, for your date work.
In order to parse the month abbreviation in all upper case (like SEP) we need to instruct it to apply case insensitive parsing.
We can use DateTimeFormatterBuilder to build a DateTimeFormatter with such an instruction.
private static final DateTimeFormatter oracleFormatter
= new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("dd-MMM-uu")
.toFormatter(Locale.ROOT);
The rest goes smoothly:
String stringFromOracle = "01-SEP-22";
LocalDate date = LocalDate.parse(stringFromOracle, oracleFormatter);
String formattedString = date.toString();
System.out.println(formattedString);
Output is:
2022-09-01
For generating the string I am exploiting the fact that LocalDate.toString() gives the format that you asked for, so I am not using any formatter explicitly. The format is known as ISO 8601 and as this name says, is an international standard.
Suggestions for improvement
Don’t retrieve your date as a String from Oracle. Retrieve a LocalDate directly and save the parsing.
Don’t convert a date from one string format to another. In your program keep the date as a LocalDate. If you need to take string input (which is not the case here), parse the string into a LocalDate immediately. Only when you need to give string output (to the user or in data exchange with another system, for example), format the LocalDate into a string in the required format.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
Question: Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2
You can simply use DateTimeFormatter:
public String convertDate(String dateStr) throws ParseException {
String[] split = dateStr.split("-");
split[1] = split[1].substring(0, 1).toUpperCase() + split[1].substring(1).toLowerCase();
dateStr = String.join("-", split);
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MMM-yy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(dateStr, dateFormatter);
return date.toString();
}
#Test
public void test_convertDate() throws ParseException {
assertEquals("2022-09-01", convertDate("01-SEP-22"));
}
I have a queue that listens to a topic and my listener receives a DTO.
I need to parse the String to LocalDateTime but I'm getting this error
org.springframework.messaging.converter.MessageConversionException: Could not read JSON: Text '2020-06-18 11:12:46' could not be parsed at index 10
Here is the message details
{"id":444, "details":{"TYPE":[1]},"dateOccurred":"2020-06-18 11:12:46"}"]
And here is how I set it in my DTO
public class PlanSubscriptionDto {
private Long id;
private Map<String, List<Long>> details;
private LocalDateTime dateOccurred;
public void setDateOccurred(String dateTime) {
this.dateOccurred = LocalDateTime.parse(dateTime, DateTimeFormatter.ISO_DATE_TIME);
//ive also tried this
//this.dateOccurred = LocalDateTime.parse(dateTime, DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG));
}
}
Thank you for your help!
Any advice would we great.
Use a format pattern string to define the format.
public class PlanSubscriptionDto {
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
private Long id;
private Map<String, List<Long>> details;
private LocalDateTime dateOccurred;
public void setDateOccurred(String dateTime) {
this.dateOccurred = LocalDateTime.parse(dateTime, FORMATTER);
}
}
Why didn’t your code work?
ISO 8601 format has a T between the date and the time. There’s no T in your date-time string, so DateTimeFormatter.ISO_DATE_TIME cannot parse it.
Variants
Now we’re at it, I’d like to show a couple of other options. Taste differs, so I can’t tell which one you’ll like the best.
You may put in the T to obtain ISO 8601 format. Then you will need no explicit formatter. The one-arg LocalDateTime.parse() parses ISO 8601 format.
public void setDateOccurred(String dateTime) {
dateTime = dateTime.replace(' ', 'T');
this.dateOccurred = LocalDateTime.parse(dateTime);
}
Or sticking to the formatter and the space between date and time, we can define the formatter in this wordier way:
private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.toFormatter();
What we get for the extra code lines is (1) more reuse of built-in formatters (2) this formatter will accept time without seconds and time with a fraction of second too because DateTimeFormatter.ISO_LOCAL_TIME does.
Link
Wikipedia article: ISO 8601
I just learned that this is also an option for the parsing :)
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "uuuu-MM-dd HH:mm:ss")
private LocalDateTime dateOccurred;
I'm using JodaTime to get the date and time of creation of an account. The format being
2017-04-05T12:38:35.585
When I get this I store it in my database as a string so I've looked around for ways to format this from a string to LocalDate but haven't been succesful in anything I've found online. My next step is a horrible solution in my opinion to loop through the string until I find the T and remove everything after it. So I'm left with
2017-04-05.
But Ideally if possible have the date as
05/04/2017
Use the ISODateTimeFormat to get a LocalDateTime and from this get the LocalDate.
Be careful to use the right Locale
String input="2017-04-05T12:38:35.585";
LocalDateTime ldt = ISODateTimeFormat.localDateOptionalTimeParser()
.withLocale(Locale.ENGLISH)
.parseLocalDateTime(input);
System.out.println(ldt.toLocalDate());//prints 2017-04-05
I'm using joda-time 2.7.
LocalDateTime class has a constructor that takes a String and parses it. Then you just call toString() method with the pattern you want:
String input = "2017-04-05T12:38:35.585";
LocalDateTime d = new LocalDateTime(input);
System.out.println(d.toString("dd/MM/yyyy"));
Output:
05/04/2017
Note: you can also use ISODateTimeFormat to parse and a DateTimeFormatter instead of toString() to get the output:
LocalDateTime d = ISODateTimeFormat.localDateOptionalTimeParser().parseLocalDateTime(input);
DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/yyyy");
System.out.println(fmt.print(d));
The output will be the same.
I have a string "2015-09-17T12:00". How can I convert this String to LocalDateTime in format "yyyy-MM-dd HH:mm" and then convert it back to String?
you can Replace T with whitespace(s):
String str="2015-09-17T12:00";
str.replace("T"," ");
afterwards convert to Date using SimpleDateFormat;
We can go with DateTimeFormatter, its thread safety.
Refer to below url:
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
sample program on converting String to Local Date Time
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd 'T' HH:mm");
LocalDateTime localDateTime = LocalDateTime.parse("2019-18-04 T 18:51", formatter);
Local Date time provides lot of method to get the hours or minutes or seconds
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html
If I already have a date's month, day, and year as integers, what's the best way to use them to create a LocalDate object? I found this post String to LocalDate , but it starts with a String representation of the date.
Use LocalDate#of(int, int, int) method that takes year, month and dayOfMonth.
You can create LocalDate like this, using ints
LocalDate inputDate = LocalDate.of(year,month,dayOfMonth);
and to create LocalDate from String you can use
String date = "04/04/2004";
inputDate = LocalDate.parse(date,
DateTimeFormat.forPattern("dd/MM/yyyy"));
You can use other formats too but you have to change String in forPattern(...)
In addition to Rohit's answer you can use this code to get Localdate from String
String str = "2015-03-15";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dateTime = LocalDate.parse(str, formatter);
System.out.println(dateTime);