Java - Parse date with optional seconds [duplicate] - java

This question already has answers here:
How do I simply parse a date without a year specified?
(5 answers)
DateTimeFormatter could not be parsed using "HH:mm E d MMM YYYY" pattern
(2 answers)
Closed 4 years ago.
Given this date I want to parse: 15th Dec 16:00 +01:00
with this code
Map<Long, String> ordinalNumbers = new HashMap<>(42);
ordinalNumbers.put(1L, "1st");
ordinalNumbers.put(2L, "2nd");
ordinalNumbers.put(3L, "3rd");
ordinalNumbers.put(21L, "21st");
ordinalNumbers.put(22L, "22nd");
ordinalNumbers.put(23L, "23rd");
ordinalNumbers.put(31L, "31st");
for (long d = 1; d <= 31; d++) {
ordinalNumbers.putIfAbsent(d, "" + d + "th");
}
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendText(ChronoField.DAY_OF_MONTH, ordinalNumbers)
.appendPattern(" MMM HH:mm[:ss] xxx")
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter().withLocale(Locale.ENGLISH);
ZonedDateTime eventDate = ZonedDateTime.parse("15th Dec 16:00 +01:00", formatter);
but I always get
java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: {DayOfMonth=15, MonthOfYear=12, OffsetSeconds=3600},ISO resolved to 16:00 of type java.time.format.Parsed
You can try it out online here: https://repl.it/repls/NaiveRegularEquation
Please tell me what I do wrong.
UPDATE:
The missing year was the problem.
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendText(ChronoField.DAY_OF_MONTH, ordinalNumbers)
.appendPattern(" MMM HH:mm[:ss] xxx")
.parseDefaulting(ChronoField.YEAR, 2018)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter().withLocale(Locale.ENGLISH);

Specify year
ZonedDateTime needs a year field, while you did not provide it.
You can set a default value:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseDefaulting(ChronoField.YEAR_OF_ERA, ZonedDateTime.now().getYear()) // set default year
.appendText(ChronoField.DAY_OF_MONTH, ordinalNumbers)
.appendPattern(" MMM HH:mm[:ss] xxx")
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter().withLocale(Locale.ENGLISH);

Related

Convert string to LocalDateTime or OffsetDateTime [duplicate]

This question already has answers here:
Can't parse String to LocalDate (Java 8)
(2 answers)
Difference between year-of-era and week-based-year?
(7 answers)
Closed 2 years ago.
I have the following code:
String dateTimeInStr = "17-Jul-2020 12:12";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-YYYY HH:mm");
// OffsetDateTime offsetDateTime = OffsetDateTime.parse(dateTimeInStr, formatter);
LocalDateTime localDateTime = LocalDateTime.parse(dateTimeInStr, formatter);
System.out.println(localDateTime);
// System.out.println(offsetDateTime);
As you can see I try convert string 17-Jul-2020 12:12 to the LocalDateTime or OffsetDateTime. But nothing works.
Text '17-Jul-2020 12:12' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {WeekBasedYear[WeekFields[MONDAY,1]]=2020, MonthOfYear=7, DayOfMonth=17},ISO resolved to 12:12 of type java.time.format.Parsed
Does anyone know how to fix this issue? Thanks in advance.
Case-sensitive
You are using uppercase 'YYYY' which is the week year. Try with lowercase 'yyyy':
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm");
Locale
And specify a Locale for the human language and cultural norms used in translating the name of month.
DateTimeFormatter formatter =
DateTimeFormatter
.ofPattern("dd-MMM-yyyy HH:mm")
.withLocale( Locale.US );
See this code run live at IdeOne.com.
2020-07-17T12:12

Parse a String with week and year into a LocalDate [duplicate]

This question already has answers here:
How to parse date from string with year and week using java.time
(3 answers)
Closed 3 years ago.
The kind of String I want to parse : "36/2017", with 36 the week of the year, 2017 the year.
My code :
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("w/uuuu")
.parseDefaulting(ChronoField.DAY_OF_WEEK, 1)
.toFormatter();
LocalDate date = LocalDate.parse("36/2017", formatter);
I added a default day.
I have this message :
java.time.format.DateTimeParseException: Text '36/2017' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {WeekOfWeekBasedYear[WeekFields[MONDAY,4]]=36, Year=2017, DayOfWeek=1},ISO of type java.time.format.Parsed
Any idea ?
Thank you !
From the docs: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
You should use uppercase Y's if you are using weeks.
public static void main(String[] args) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("w/YYYY")
.parseDefaulting(ChronoField.DAY_OF_WEEK, 1)
.toFormatter();
LocalDate date = LocalDate.parse("36/2017", formatter);
}
The pattern is wrong. You must set the following string
"w/YYYY"
DateTimeFormatter formatter = new
DateTimeFormatterBuilder()
.appendPattern("w/YYYY")
.parseDefaulting(ChronoField.DAY_OF_WEEK, 1)
.toFormatter();
LocalDate date = LocalDate.parse("36/2017", formatter);

How to get in this date format? [duplicate]

This question already has answers here:
How can I change the date format in Java? [duplicate]
(10 answers)
Change date format in a Java string
(22 answers)
Java string to date conversion
(17 answers)
Closed 4 years ago.
I am getting two date fields from JSON as text like this May 22 12:05:41 UTC 2018 and 2018-05-22 12:05:41.512 but I have to change to MM-dd-yyyy HH:mm:ss format.
Just to be clear - date/time objects are format agnostic. They are simply containers for the amount of time which has passed since a fixed point in time (usually the Unix Epoch), so you can't change their format per se.
However, you can, generate a String of a prescribed pattern.
When dealing with date/time in Java you should make use of the date/time APIs introduced in Java 8 (or the ThreeTen back port)
For example...
String date1 = "May 22 12:05:41 UTC 2018";
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
LocalDateTime ldt1 = LocalDateTime.parse(date1, format1);
String date2 = "2018-05-22 12:05:41.512";
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
LocalDateTime ldt2 = LocalDateTime.parse(date2, format2);
DateTimeFormatter format3 = DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss", Locale.ENGLISH);
System.out.println(ldt1.format(format3));
System.out.println(ldt2.format(format3));
Which outputs...
05-22-2018 12:05:41
05-22-2018 12:05:41
Since one of your inputs has a timezone associated with it, it would be appropriate to take it into consideration
ZonedDateTime zdt = ZonedDateTime.parse(date1, format1);
LocalDateTime ldt1 = zdt.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
which outputs (for my current location)
05-22-2018 22:05:41
You can use this code
DateFormat format = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
DateFormat inputFormat1 = new SimpleDateFormat("MMM dd HH:mm:ss z yyyy");
DateFormat inputFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String date1 = "May 22 12:05:41 UTC 2018";
String date2 = "2018-05-22 12:05:41.512";
System.out.println(format.format(inputFormat1.parse(date1)));
System.out.println(format.format(inputFormat2.parse(date2)));

Month Year In String to Date Java 8 [duplicate]

This question already has answers here:
How to convert date from MM/YYYY to MM/DD/YYYY in Java
(4 answers)
Closed 4 years ago.
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/yyyy");
LocalDate parsedDate = LocalDate.parse(entryOne.getKey(), dateFormat)
Getting exception
Text '03/2018' could not be parsed: Unable to obtain LocalDate from TemporalAccessor:
How to parse this string and convert to Date using Java 8 having default first day of the month. Something what we do using.
TemporalAdjusters.firstDayOfMonth()
You have two choices for converting a MM/yyyy string into a LocalDate:
Parse as YearMonth then convert to LocalDate:
String date = "04/2018";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/yyyy");
YearMonth yearMonth = YearMonth.parse(date, dateFormat);
LocalDate parsedDate = yearMonth.atDay(1);
System.out.println(parsedDate); // prints: 2018-04-01
Use a DateTimeFormatter with a default day-of-month defined:
String date = "04/2018";
DateTimeFormatter dateFormat = new DateTimeFormatterBuilder()
.appendPattern("MM/yyyy")
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter();
LocalDate parsedDate = LocalDate.parse(date, dateFormat);
System.out.println(parsedDate); // prints: 2018-04-01
Here's what works for me:
String dateAsString = "03/2018";
DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/yyyy");
DateTime dt = fmt.parseDateTime(dateAsString);
LocalDateTime ldt = new LocalDateTime(dt);
int dayOfWeek = ldt.getDayOfWeek(); //has value of 4 since Thursday was the first day of March

How to convert an Instant to a date format? [duplicate]

This question already has answers here:
UnsupportedTemporalTypeException when formatting Instant to String
(7 answers)
Closed 7 years ago.
I can convert a java.util.Date to a java.time.Instant (Java 8 and later) this way:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 8);
cal.set(Calendar.MINUTE, 30);
Date startTime = cal.getTime();
Instant i = startTime.toInstant();
Can anybody let me know about the convert that instant to date with a specific date & time format? i.e 2015-06-02 8:30:00
I have gone through api but could not find a satisfactory answer.
If you want to convert an Instant to a Date:
Date myDate = Date.from(instant);
And then you can use SimpleDateFormat for the formatting part of your question:
SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
String formattedDate = formatter.format(myDate);
An Instant is what it says: a specific instant in time - it does not have the notion of date and time (the time in New York and Tokyo is not the same at a given instant).
To print it as a date/time, you first need to decide which timezone to use. For example:
System.out.println(LocalDateTime.ofInstant(i, ZoneOffset.UTC));
This will print the date/time in iso format: 2015-06-02T10:15:02.325
If you want a different format you can use a formatter:
LocalDateTime datetime = LocalDateTime.ofInstant(i, ZoneOffset.UTC);
String formatted = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss").format(datetime);
System.out.println(formatted);
try Parsing and Formatting
Take an example
Parsing
String input = ...;
try {
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("MMM d yyyy");
LocalDate date = LocalDate.parse(input, formatter);
System.out.printf("%s%n", date);
}
catch (DateTimeParseException exc) {
System.out.printf("%s is not parsable!%n", input);
throw exc; // Rethrow the exception.
}
Formatting
ZoneId leavingZone = ...;
ZonedDateTime departure = ...;
try {
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
String out = departure.format(format);
System.out.printf("LEAVING: %s (%s)%n", out, leavingZone);
}
catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", departure);
throw exc;
}
The output for this example, which prints both the arrival and departure time, is as follows:
LEAVING: Jul 20 2013 07:30 PM (America/Los_Angeles)
ARRIVING: Jul 21 2013 10:20 PM (Asia/Tokyo)
For more details check this page-
https://docs.oracle.com/javase/tutorial/datetime/iso/format.html

Categories