Month Year In String to Date Java 8 [duplicate] - java

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

Related

Subtracting a date from the current day in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a particular date format.I can subtract 2 dates but I can't achieve to subtract today's date from a future one.
I found the way to get today's date
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
Here is the way I subtract 2 dates(Strings)
public boolean DateDiff(String datep,String dater) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date1 = LocalDate.parse(datep, formatter);
LocalDate date2 = LocalDate.parse(dater, formatter);
long elapsedDays = ChronoUnit.DAYS.between(date1, date2);
I can't turn the current day to a String so I can have 2 same types of variables to subtract.What kind of type is the LocalDateTime now
To subtract dates is as easy as this one using the minusDays() function of LocalDate:
LocalDate now = LocalDate.now();
LocalDate thirtyDaysAgo = now.minusDays(30);
If you have a standard string of date, see "2020-08-27", you can parse it this way:
String date = "2020-08-27";
LocalDate thirtyDaysAgo = LocalDate.parse(date).minusDays(30);
System.out.println(thirtyDaysAgo); //prints 2020-07-28
If you have a special format of date, see "2020/08/27", you parse it this way:
String date = "2020/08/27";
LocalDate thirtyDaysAgo = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy/MM/dd")).minusDays(30);
System.out.println(thirtyDaysAgo); //prints 2020-07-28
To turn a LocalDate to a String with format, you do it this way:
LocalDate date = LocalDate.now();
String formatedDate = date.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
System.out.println(formatedDate); //prints 2020/08/27
Use LocalDate instead of LocalDateTime to get today's date
LocalDate currentDate = LocalDate.now();
For some reason if you still want to use LocalDateTime to get today's date, this is how you can do it
LocalDateTime currentDateTime = LocalDateTime.now();
LocalDate currentDate = currentDateTime.toLocalDate();
if you want to convert currentDate to String in your desired format as follows:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String currentDateString = currentDate.format(formatter);
if both the dates you have are of type LocalDate, then you can find the number of days in between them as follows:
public long DateDiff(LocalDate date1,LocalDate date2) {
return Duration.between(date1, date2).toDays();
}
if both the dates you have are of type String, then you can find the number of days in between them as follows:
public long DateDiff(String dateString1,String dateString2) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date1 = LocalDate.parse(dateString1, formatter);
LocalDate date2 = LocalDate.parse(dateString2, formatter);
return Duration.between(date1, date2).toDays();
}
Hope that solves your problem
You can use joda-time library its a bliss when working with dates in java.
Subtract 2 dates
DateTime yesterday = new DateTime().withTimeAtStartOfDay().minusMinutes(10);
DateTime twoDaysFromToday = new DateTime().withTimeAtStartOfDay().plusDays(2);
Days.daysBetween(yesterday.toLocalDate(), twoDaysFromToday.toLocalDate()).getDays();
Use LocalDate (not LocalDateTime).
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate today = LocalDate.now(ZoneId.of("Asia/Calcutta"));
LocalDate futureDate = LocalDate.parse("26/09/2020", formatter);
long elapsedDays = ChronoUnit.DAYS.between(today, futureDate);
System.out.println("Days until future date: " + elapsedDays);
Output was when running just now:
Days until future date: 29

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);

Java: Unable to obtain LocalDate from TemporalAccessor

I am trying to change the format of a String date from EEEE MMMM d to MM/d/yyyy by, first, converting it into a LocalDate and then applying a formatter of a different pattern to the LocalDate before parsing it into String again.
Here's my code:
private String convertDate(String stringDate)
{
//from EEEE MMMM d -> MM/dd/yyyy
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("EEEE MMMM d"))
.toFormatter();
LocalDate parsedDate = LocalDate.parse(stringDate, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/d/yyyy");
String formattedStringDate = parsedDate.format(formatter2);
return formattedStringDate;
}
However, I get this exception message that I don't really understand:
Exception in thread "main" java.time.format.DateTimeParseException: Text 'TUESDAY JULY 25' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {DayOfWeek=2, MonthOfYear=7, DayOfMonth=25},ISO of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
As the other answers already said, to create a LocalDate you need the year, which is not in the input String. It has only day, month and day of the week.
To get the full LocalDate, you need to parse the day and month and find a year in which this day/month combination matches the day of the week.
Of course you could ignore the day of the week and assume that the date is always in the current year; in this case, the other answers already provided the solution. But if you want to find the year that exactly matches the day of the week, you must loop until you find it.
I'm also creating a formatter with a java.util.Locale, to make it explicit that I want month and day of week names in English. If you don't specify a locale, it uses the system's default, and it's not guaranteed to always be English (and it can be changed without notice, even at runtime).
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("EEEE MMMM d"))
// use English Locale to correctly parse month and day of week
.toFormatter(Locale.ENGLISH);
// parse input
TemporalAccessor parsed = formatter.parse("TUESDAY JULY 25");
// get month and day
MonthDay md = MonthDay.from(parsed);
// get day of week
DayOfWeek dow = DayOfWeek.from(parsed);
LocalDate date;
// start with some arbitrary year, stop at some arbitrary value
for(int year = 2017; year > 1970; year--) {
// get day and month at the year
date = md.atYear(year);
// check if the day of week is the same
if (date.getDayOfWeek() == dow) {
// found: 'date' is the correct LocalDate
break;
}
}
In this example, I started at year 2017 and tried to find a date until back to 1970, but you can adapt to the values that fits your use cases.
You can also get the current year (instead of some fixed arbitrary value) by using Year.now().getValue().
The documentation for LocalDate says, that
LocalDate is an immutable date-time object that represents a date,
often viewed as year-month-day. For example, the value "2nd October
2007" can be stored in a LocalDate.
In your case, the input String is missing an important component of LocalDate , i.e the year. What you have basically is month and day. So, you can use a class suited to that MonthDay. Using that your code can be modified to :
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("EEEE MMMM d"))
.toFormatter();
MonthDay monthDay = MonthDay.parse(stringDate, formatter);
LocalDate parsedDate = monthDay.atYear(2017); // or whatever year you want it at
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/d/yyyy");
String formattedStringDate = parsedDate.format(formatter2);
System.out.println(formattedStringDate); //For "TUESDAY JULY 25" input, it gives the output 07/25/2017
Here is the minor change which you need to implement:
private static String convertDate(String stringDate)
{
//from EEEE MMMM d -> MM/dd/yyyy
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("EEEE MMMM dd")
.parseDefaulting(ChronoField.YEAR, 2017)
.toFormatter();
LocalDate parsedDate = LocalDate.parse(stringDate, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/d/yyyy");
String formattedStringDate = parsedDate.format(formatter2);
return formattedStringDate;
}
Add the default chronological year in the formatter using .parseDefaulting(ChronoField.YEAR, 2017)
Call the method using the argument "Tuesday July 25" like this convertDate("Tuesday July 25");
Another option is to do the following (just like the other answers a bit hacky), assuming of course you want the date to fall in the current year:
LocalDate localDate = LocalDate.parse(stringDate + " " +LocalDate.now().getYear(), DateTimeFormatter.ofPattern("EEEE MMMM d");

convert shortdate to LocalDate

Hi i have a short date format with me in the pattern E dd/MM , Is there any way i can convert it to LocalDate.
String date = "Thu 07/05";
String formatter = "E dd/MM";
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
final LocalDate localDate = LocalDate.parse(date, formatter);`
But it throws an exception java.time.format.DateTimeParseException: Text 'Thu 07/05' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=5, DayOfMonth=7, DayOfWeek=4},ISO of type java.time.format.Parsed
Is there any way we can fix this issue ?
All you have is a month and a day - so you can create a MonthDay (to create a LocalDate you would also need a year):
MonthDay md = MonthDay.parse(date, formatter);
If you want a LocalDate, you can use the MonthDay as a starting point:
int year = Year.now().getValue();
LocalDate localDate = md.atYear(year);
Or alternatively you can use a default year in your formatter:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern(pattern)
.parseDefaulting(ChronoField.YEAR, year)
.toFormatter(Locale.US);
LocalDate localDate = LocalDate.parse(date, formatter);
The benefit of this method is that it will also check that the day of week (Thursday) is correct.

Why my pattern("yyyyMM") cannot parse with DateTimeFormatter (java 8)

When I using SimpleDateFormat, it can parse.
SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
format.setLenient(false);
Date d = format.parse(date);
But When I use Java 8 DateTimeFormatter,
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
LocalDate localDate = LocalDate.parse(date, formatter);
it throws
java.time.format.DateTimeParseException: Text '201510' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2015, MonthOfYear=10},ISO of type java
.time.format.Parsed
String value for date is "201510".
Ask yourself the question: which day should be parsed with the String "201510"? A LocalDate needs a day but since there is no day in the date to parse, an instance of LocalDate can't be constructed.
If you just want to parse a year and a month, you can use the YearMonth object instead:
YearMonth localDate = YearMonth.parse(date, formatter);
However, if you really want to have a LocalDate to be parsed from this String, you can build your own DateTimeFormatter so that it uses the first day of the month as default value:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("yyyyMM")
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter();
LocalDate localDate = LocalDate.parse(date, formatter);
You can use a YearMonth and specify the day you want (say the first for example):
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
LocalDate localDate = YearMonth.parse(date, formatter).atDay(1);
Or if the day is irrelevant, just use a YearMonth.

Categories