localdate parsing can't parse hours and minutes - java

I need to get the date from a String, the format is the following: uuuu-MM-dd HH:mm
The input has that format and I want the same format for my dates (year-month-day hour:minutes). When I did this:
LocalDate aux = LocalDate.parse(times.get(index),DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm "));
with this input: 2017-12-05 20:16
I get only this: 2017-12-05
I don't know why, I've tried a lot of formats and always lost the hours and minutes. Any idea?

LocalDate only has year, month, day fields. It cannot contain time of day data.
Use LocalDateTime instead.
LocalDateTime aux = LocalDateTime.parse("2017-12-05 20:16", DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm"));

Related

How to Parse Any Datetime format to yyyy-MM-dd in java

I have a date field that is populated dynamically, and I need that field in the format yyyy-MM-dd
For a input date of format 1994-08-01 14:37:44 this is giving a Exception
java.time.format.DateTimeParseException: Text '1994-08-01 14:37:44' could not be parsed, unparsed text found at index 10
This is one of the many other ways I tried LocalDateTime.parse("1994-08-01 14:37:44",DateTimeFormatter.ofPattern(yyyy-MM-dd));
Is there a way to convert all date/datetime to yyyy-MM-dd format?
please help
Thanks
You have a date and time component but you're only using a date format to parse it to a LocalDateTime value, this will fail because LocalDateTime needs the time component in order to work
Start by parsing the full text
String input = "1994-08-01 14:37:44";
LocalDateTime ldt = LocalDateTime.parse(input, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
Then use a DateTimeFormatter to format it the way you want
String formatted = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(ldt);
System.out.println(formatted);
which prints
1994-08-01
Depending on your needs, you could also convert the LocalDateTime value to a LocalDate and format it, it's the same result, but you might have need of the LocalDate for other things, who knows...
String formatted = ldt.toLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
Try it like this. You can extract the LocalDate part.
LocalDate ldt = LocalDateTime.parse("1994-08-01 14:37:44",
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
Prints
1994-08-01

DateTimeParseException: Text '2019-06-07 12:18:16' could not be parsed

I have following code to convert an Instant to String then convert it back to I
String timestampString = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));
LOGGER.info("timestampString: " + timestampString);
Instant instant =
LocalDateTime.parse(timestampString,
DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")).toInstant(ZoneOffset.UTC);
it print the timestampString as: 2019-06-07 12:45:57
and failed at parse the string:
java.time.format.DateTimeParseException: Text '2019-06-07 12:45:57' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {MinuteOfHour=45, HourOfAmPm=0, NanoOfSecond=0, SecondOfMinute=57, MilliOfSecond=0, MicroOfSecond=0},ISO resolved to 2019-06-07 of type java.time.format.Parsed
why it cannot parse it even though that's the same format I convert the timestamp to?
Use HH for hour of day instead of hh
The problem that you are asking about is that you are using lowercase hh in your format pattern string (both times). You need uppercase HH for hour day from 00 through 23. hh is for hour within AM or PM from 01 through 12. So what went wrong was that java.time didn’t know whether 12 in your string referred to 12 AM or 12 PM and refused to make a guess for you.
If you read the exception message closely you will also notice that it says that HourOfAmPm=0 was parsed. It doesn’t say HourOfDay.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timestampString = LocalDateTime.now().format(formatter);
System.out.println("timestampString: " + timestampString);
Instant instant = LocalDateTime.parse(timestampString, formatter)
.toInstant(ZoneOffset.UTC);
System.out.println("instant: " + instant);
When I ran this snippet just now, I got this output:
timestampString: 2019-06-08 19:22:51
instant: 2019-06-08T19:22:51Z
This is wrong! I ran the snippet around 17:22 UTC, not 19:22. Since Denmark is still using summer time (damn), the local time here was 19:22, which was used for the result and translated into the same wall clock time in UTC, not the same instant. You should always pass your desired time zone to the now method to avoid such bugs. Since you wanted UTC:
String timestampString = LocalDateTime.now(ZoneOffset.UTC).format(formatter);
timestampString: 2019-06-08 17:27:57
instant: 2019-06-08T17:27:57Z
Still better, don’t use LocalDateTime for holding something that you want to use as a moment in time. Use Instant, OffsetDateTime or ZonedDateTime instead.
There is more information on using hh, HH or kk for formatting and parsing hour values in this question and its answers: Difference between java HH:mm and hh:mm on SimpleDateFormat. The question is asking about the notoriously troublesome SimpleDateFormat, but the answers are valid for DateTimeFormatter too.

Unable to obtain LocalDate from TemporalAccessor using quarters

I am trying to parse some date-string into a date value, however, using the below code, I am getting an exception:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("Q'Q'uuuu - MMM");
String d = "3Q2016 - Aug";
System.out.println(LocalDate.parse(d, formatter));
The exception is below
java.time.format.DateTimeParseException: Text '3Q2016 - Aug' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=8, QuarterOfYear=3, Year=2016},ISO of type java.time.format.Parsed
Looking at the exception, I see the correct data, but it is not able to be parsed for some reason.
Other similar topics i see suggest using LocalDate or LocalDateTime, but neither work.
Its because the specified string does not have a specific date to select. You probably need to use YearMonth instead of LocalDateTime and then convert it using YearMonth.atDay(1) to get the first day of the month.
As said in this answer, you need to specify a day to be able to parse to a LocalDate. So one solution is to parse to a YearMonth instead and convert to a LocalDate by specifying a day afterwards.
Or you create a DateTimeFormatter with a fixed day in the first place:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("Q'Q'uuuu - MMM")
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter(Locale.US);
String d = "3Q2016 - Aug";
System.out.println(LocalDate.parse(d, formatter));
I used toFormatter(Locale.US) to make the example work in all environments. In an environment where the input string matches the current locale, you can use toFormatter() instead.
Try adding a Time part to the date -
String str = "2Q1986 - Apr - 08 T00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("Q'Q'yyyy - MMM - dd 'T'hh:mm");
LocalDate dateTime = LocalDate.parse(str, formatter);

Convert string of digits to date, compare against current date

Let's say I have a text file with names, an order number, and a date an order was placed. If the dates are in the format of MMDDYY (080315 = August 3, 2015 for example) is there a way I can parse that, convert into date format, then compare it to the current date? I want it so that if they submit a date in this format that is after the current day, it is invalid.
I would recommend using the Joda-Time library.
Joda-Time Website
Then you can do something like.
DateFormat df = new SimpleDateFormat("MMddyy");
Date date = df.parse("070791");
LocalDate ld = new LocalDate(date);

Convert String to GMT timezone date. JAVA

I am getting a date/time string from web in the format of yyyy-mm-dd HH:MM:SS and it is in UTC.
I have to create a Date object and print the date object in GMT format, but I don't want the to change, for example if I read the date as 2014-10-22 09:00:00, then it should be displayed as 2014-10-22 09:00:00 GMT instead of 2014-10-22 13:30:00
How do I do this? Please suggest me.
(FYI, Currently, UTC time is 10:25 AM, in india current time is 3:55 PM).
I am using Jaxb parser to parse the XML. Any suggestions are invited
You could use a SimpleDateFormat to parse the date, and then reformat it to a different timezone.
String toTimeZone = "GMT";
String fromTimeZone = "UTC";
String stingvalue = "2014-10-14 03:05:39";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone(fromTimeZone));
Date parsedDate = dateFormat.parse(stingvalue);
dateFormat.setTimeZone(TimeZone.getTimeZone(toTimeZone));
String newDate = dateFormat.format(parsedDate);
Explanation
The Java Date class counts time in milliseconds from January 1, 1970 00:00:00.000 GMT. As such, your Dates are time zone neutral. To get date in a different time zone, simply format it differently

Categories