I am trying to parse a string "Sunday, July 4, 2021" to LocalDate as the following:
string this.selectedDate = "Sunday, July 4, 2021";
LocalDate date = LocalDate.parse(this.selectedDate);
But I am getting this error:
java.time.format.DateTimeParseException: Text 'Sunday, July 4, 2021' could not be parsed at index 0
How can I convert such a string full date to the LocalDate?
Try it like this.
String s = "Sunday, July 4, 2021";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEEE, LLLL d, yyyy");
LocalDate ld = LocalDate.parse(s, dtf);
System.out.println(ld);
prints
2021-07-04
Read up on DateTimeFormatter if you want to change the output format.
Note: If the day of the week is wrong for the numeric day of the month, you will get a parsing error. To avoid this, just skip over or otherwise ignore the day of the week.
Related
I get the error:
java.time.format.DateTimeParseException:
Text 'Jun 4 2020 8:58:15 AM' could not be parsed at index 0
String ajourTsAdjusted = "Jun 4 2020 8:58:15 AM";
DateTimeFormatter dt = DateTimeFormatter.ofPattern("MMM d yyyy h:mm:ss a");
LocalDateTime ajDate = LocalDateTime.parse(ajourTsAdjusted, dt);
Can someone see what I did not do right here?
Regards Flemming
I am assuming your system language is not English.
This assumption is made because of your error language stating (..) cannot be parsed at index 0, that is the beginning of the date resp. pattern.
There, you have an abbreviation of a month name and those abbreviations differ from language to language. In my country, Jun is the abbreviation for June in English, but by coincidence, it is the German abbreviation for Juni, too, which makes this code work on my system.
The DateTimeFormatter will use the language setting of your system if you don't provide a different/specific Locale.
To make sure an English datetime will be parsed, provide a Locale to the DateTimeFormatter:
public static void main(String[] args) {
String ajourTsAdjusted = "Jun 4 2020 8:58:15 AM";
DateTimeFormatter dt = DateTimeFormatter.ofPattern("MMM d yyyy h:mm:ss a",
Locale.ENGLISH);
LocalDateTime ajDate = LocalDateTime.parse(ajourTsAdjusted, dt);
System.out.println(ajDate);
}
This will output the ISO-formatted datetime String like this:
2020-06-04T08:58:15
String oldDate = "04-07-19 02:41:39.063000000 PM";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("dd-MM-YY HH:mm:ss")
.appendFraction(ChronoField.NANO_OF_SECOND, 1, 9, true)
.padNext(1)
.appendText(ChronoField.AMPM_OF_DAY)
.toFormatter();
LocalDate parseDate = LocalDate.parse(oldDate, formatter);
My date from the DB is "04-07-19 02:41:39.063000000 PM"
and i want to parse the date and convert it to my convenient form.
but when i try to parse the date using the DateTimeFormatter mentioned above the code throws exception..
the new date should be of the format mentioned below
String newDate = parseDate.format(DateTimeFormatter.ofPattern("dd-MMMM-uuuu"));
can someone help me to track the error?
exception iam getting is
Exception in thread "main" java.time.format.DateTimeParseException: Text '04-07-19 02:41:39.063000000 PM' could not be parsed at index 55
In your pattern you had few errors. First of all padNext() add a padding to a fixed width. In your case it should be 28 or something like that. I've just replaced it with appendLiteral(' '). Then HH represends hours in 24hour day, it won't work with AM/PM. Last thing was year, YY represends "week-based-year" according to JavaDoc (not exactly sure what that means) - had to change to yy for it to work.
Working pattern:
String oldDate = "04-07-19 02:41:39.063000000 PM";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("dd-MM-yy hh:mm:ss")
.appendFraction(ChronoField.NANO_OF_SECOND, 1, 9, true)
.appendLiteral(' ')
.appendText(ChronoField.AMPM_OF_DAY)
.toFormatter();
LocalDate parseDate = LocalDate.parse(oldDate, formatter);
System.out.println(parseDate);
I need to convert the string "Thursday 30 May 2019 - 02:00 PM" to (dd MMM hh:mm a) DateTimeFormat "06 June 01:54 PM"(date).
Here is my code:
// last update date is : Thursday 30 May 2019 - 02:00 PM
String lastUpadte WebUI.getText(findTestObject("Stock prices/date time"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy");
LocalDate date = LocalDate.parse(lastUpadte, formatter);
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>" + date);
The dates and times were revamped for Java 8, introducing types like LocalDateTime which are very easy to use. The lack of a year in one of your date strings is an added complexity, but using these features, you could have :
String dtStr1 = "06 June 01:54 PM";
DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
.appendPattern("dd MMMM hh:mm a")
.parseDefaulting(ChronoField.YEAR, 2019)
.toFormatter();
LocalDateTime date1 = LocalDateTime.parse(dtStr1, formatter1);
String dtStr2 = "Thursday 30 May 2019 - 02:00 PM";
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("EEEE dd MMM uuuu - hh:mm a");
LocalDateTime date2 = LocalDateTime.parse(dtStr2, formatter2);
System.out.println(date1);
System.out.println(date2);
Output is :
2019-06-06T13:54
2019-05-30T14:00
The formatter patterns are listed in :
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
To get a java.time.LocalDateTime with the same format as "Thursday 30 May 2019 - 02:00 PM":
LocalDateTime ldt = LocalDateTime.parse("Thursday 30 May 2019 - 02:00 PM",
DateTimeFormatter.ofPattern("EEEE dd MMMM uuuu '-' hh':'mm a")));
For those with the same format as "06 June 01:54 PM":
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("dd MMMM hh':'mm a")
.parseDefaulting(ChronoField.YEAR, 2019)
.toFormatter();
LocalDateTime ldt = LocalDateTime.parse("06 June 01:54 PM", formatter));
Note we need to specifically build the parser this way in the latter example since the year is missing, otherwise we'll get an Exception.
I have a date and I need to know the last week and last month before the date.
For example,
on July 15, 2018, Its last week was from July 2 to July 8. Its last month was June 1 to June 30.
on July 16, 2018, Its last week was from July 9 to July 15. Its last month was June 1 to June 30.
on July 17, 2018, Its last week was from July 9 to July 15. Its last month was June 1 to June 30.
It is different from get-date-of-first-day-of-week-based-on-localdate-now-in-java-8, my problem is to get last week or last month.
You can use these helper methods.
public static LocalDate[] getPreviousWeek(LocalDate date) {
final int dayOfWeek = date.getDayOfWeek().getValue();
final LocalDate from = date.minusDays(dayOfWeek + 6); // (dayOfWeek - 1) + 7
final LocalDate to = date.minusDays(dayOfWeek);
return new LocalDate[]{from, to};
}
public static LocalDate[] getPreviousMonth(LocalDate date) {
final LocalDate from = date.minusDays(date.getDayOfMonth() - 1).minusMonths(1);
final LocalDate to = from.plusMonths(1).minusDays(1);
return new LocalDate[]{from, to};
}
There are in fact many ways to write this. I would suggest you to do some exploration on your own.
You can easly do that with Java 8 LocalDate, here's my solution:
import java.time.LocalDate;
LocalDate now = LocalDate.now();
LocalDate weekStart = now.minusDays(7+now.getDayOfWeek().getValue()-1);
LocalDate weekEnd = now.minusDays(now.getDayOfWeek().getValue());
LocalDate previousMonth = now.minusMonths(1);
LocalDate monthStart = previousMonth.withDayOfMonth(1);
LocalDate monthEnd = previousMonth.withDayOfMonth(previousMonth.getMonth().maxLength());
System.out.println("WeekStart:"+weekStart+", weekEnd:"+weekEnd+", monthStart:"+monthStart+", monthEnd:"+monthEnd);
Result
WeekStart:2018-07-09, weekEnd:2018-07-15, monthStart:2018-06-01, monthEnd:2018-06-30
If you change the now line with
LocalDate now = LocalDate.of(2018,07,15);
You'll get:
WeekStart:2018-07-02, weekEnd:2018-07-08, monthStart:2018-06-01, monthEnd:2018-06-30
ZonedDateTime is useful for that.
import java.time.*;
import java.time.format.DateTimeFormatter;
class DateTest
{
public static void main (String[] args) throws java.lang.Exception
{
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd MMM yyyy");
ZoneId usCentral = ZoneId.of("America/Chicago");
LocalDateTime localDateTime = LocalDateTime.of(2018, Month.JULY, 16, 9, 30);
ZonedDateTime input = ZonedDateTime.of(localDateTime, usCentral);
System.out.println("Input date = " + format.format(input));
ZonedDateTime startDate = input.minusWeeks(1).with(DayOfWeek.MONDAY);
System.out.println("Start date = " + format.format(startDate));
ZonedDateTime endDate = startDate.plusDays(6);
System.out.println("End date = " + format.format(endDate));
}
}
Output:
Input date = 16 Jul 2018
Start date = 09 Jul 2018
End date = 15 Jul 2018
Not sure if you got a Date object, hopefully you got.
From date object you can get Instant with method toInstant()
(To pasrse String to date..
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
date format must be addapted to your needs ofcourse
)
Instant.now().minus(Duration.ofDays(7))); // last week
Instant.now().minus(Duration.of(1,ChronoUnit.MONTHS)) // last month
I am trying to parse a date to convert it to epochs. I tried the solution of a similar question here without success:
String date = "Jun 4 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("LLL dd yyyy").withLocale(Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(date, formatter);
System.out.println(date+" "+ldt.toEpochSecond(ZoneOffset.UTC));
And I get Exception in thread "main" java.time.format.DateTimeParseException: Text 'Jun 4 2015' could not be parsed at index 0 even though I am fairly certain that my regular expression is correct. What am I missing here?
EDIT:
Following the comments, I changed LocalDateTime to LocalDate, but keep getting the same error:
String date = "Jun 4 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy").withLocale(Locale.ENGLISH);
LocalDate ldt = LocalDate.parse(date, formatter);
String date = "Jun 4 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy").withLocale(Locale.ENGLISH);
LocalDate ldt = LocalDate.parse(date, formatter);
parses fine. Don't put the "dd" as it won't parse days less than 10. As #JB Nizet said, you'll need to use LocalDate, not LocalDateTime.