OffsetDateTime.parse('2018-12-03T18:07:55') throwing DateTimeParseException - java-time

I believe this should work. Granted it has no specified offset, but shouldn't that then default to UTC? And if not, how can I parse a string like this into an OffsetDateTime?
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd['T'[HH:mm:ss][.SSSSS]][z][x]");
String datetime = "2018-12-03T18:07:55";
OffsetDateTime odt = OffsetDateTime.parse(datetime, formatter);
Exception thrown:
java.time.format.DateTimeParseException: Text '2018-12-03T18:07:55' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {},ISO resolved to 2018-12-03T18:07:55 of type java.time.format.Parsed

As you say, it's failing because there's no offset in the format. To work around this, you can use the same format to parse to a LocalDateTime, and then combine with a ZoneOffset to create an OffsetDateTime:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd['T'[HH:mm:ss][.SSSSS]][z][x]");
String datetime = "2018-12-03T18:07:55";
LocalDateTime ldt = LocalDateTime.parse(datetime, formatter);
OffsetDateTime odt = OffsetDateTime.of(ldt, ZoneOffset.UTC);
System.out.println(odt);

Related

DateTime parse issue using intl package dart

I have a date which is a string and looks like this:
String day = "30-11-2022 12:27";
I am trying to convert the above string to DateTime object and convert the 24hr time to 12hr. I am using the following code:
DateFormat("dd-MM-yyyy hh:mm a").parse(day);
It was working before but today the parsing is causing format exception error. The error message is shown below:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FormatException: Trying to read from 30-11-2022 12:27 at position 17
Why am I getting error while parsing now? How to fix it?
There must be a simpler solution, but it works this way:
final str = "30-11-2022 12:27";
final date = DateFormat("dd-MM-yyyy hh:mm").parse(str);
final formated = DateFormat("dd-MM-yyyy h:mm a").format(date);
The format for a 24-hr time is 'HH:mm'. The key is to call add_jm(). Just do this:
final day = '30-11-2022 12:27';
final dateTime = DateFormat('dd-MM-yyyy HH:mm').parse(day);
final formatted = DateFormat('dd-MM-yyy').add_jm().format(dateTime);
print(formatted);
The output is:
30-11-2022 12:27 PM
can try this. hope your problem solved
DateTime dateTime = DateFormat('yyyy/MM/dd h:m').parse(date);
final DateFormat formatter = DateFormat('yyyy-MM-dd h:m a');
final String formatted = formatter.format(dateTime);
It really doesn't matter for datetime that the input date is in am format or not, because you can parse it to what ever format you want. For both option when you parse your string, it will save it in regular form. So just try this:
String day = "30-11-2022 12:27";
DateTime date = normalFormat.parse(day);
and when ever you want show it as AM, just format date;
Why am I getting error while parsing now? How to fix it?
You specified a DateFormat format string that uses a, which indicates that you want to parse an AM/PM marker, but the string you try to parse is "30-11-2022 12:27", which lacks it.
If you're trying to convert a 24-hour time to a 12-hour time, those are fundamentally two different formats, so you will two different DateFormat objects. Note that the format pattern for hours is different for 12-hour times (h) than for 24-hour ones (H):
String day = "30-11-2022 12:27";
var datetime = DateFormat("dd-MM-yyyy HH:mm").parse(day);
// Prints: 30-11-2022 12:27 PM
print(DateFormat('dd-MM-yyyy hh:mm a').format(datetime));

Unparseable date error format in Spring Boot Mongo DB

MongoCollection<Document> Profile_List = db.getCollection("Profile_List");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD");
Date todaydate = format.parse(new Date().toString());
ArrayList<Document> activeList=profile.find(Filters.regex("lastActive",todayDate.toString())).into(new ArrayList<Document>());
This is the code what we have written. We are getting an “Unparseable date error”. Can someone please help?
This is wrong:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD");
Date todaydate = format.parse(new Date().toString());
The expression new Date().toString() does not return a string that conforms to the format yyyy-MM-DD, so if you try to parse it as if it is formatted that way, you will get an exception.
If you want a Date object that represents the current date and time, simply do this:
Date todaydate = new Date();
No need to convert the Date object to a string and trying to parse it.
If you need a string with the current date in the format yyyy-MM-dd then do this:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String todaydate = format.format(new Date());
Note: You used DD in your date format string but you most likely meant dd. See the API documentation of SimpleDateFormat.
If you are trying to get the current date string in yyyy-MM-dd format. You can do format it like this
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = simpleDateFormat.format(new Date());

Convert TestNG Start and Stop time to Postgres Without Time Zone

I currently have some TestNG custom reporting code that works with the local MySQL database I have been testing against. The resulting database is postgres due to issues with latest MySQL versions in AWS, in trying to convert the format of TestNG millis over I have been encountering issues with the format which I can't seem to get one that works right.
My custom report code was using the following:
report.reporting.put("startDate", testResult.getStartMillis());
report.reporting.put("endDate", testResult.getEndMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
String startDbTime = sdf.format(report.get("startDate"));
String endDbTime = sdf.format(report.get("endDate"));
When I try some of the dateformatters I am receiving indexing errors like: DateTimeParseException: Text could not be parsed at index 4
I've used some various options like offset or instant with no success.
This is a collection of some of the options I have tried.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
String startDbTime = sdf.format(report.get("startDate"));
String endDbTime = sdf.format(report.get("endDate"));
// OffsetDateTime startDbTime = OffsetDateTime.parse(startRawDbTime);
// OffsetDateTime endDbTime = OffsetDateTime.parse(endRawDbTime);
// ZonedDateTime startDbTime = ZonedDateTime.parse(startRawDbTime);
// ZonedDateTime endDbTime = ZonedDateTime.parse(endRawDbTime);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
String startRawDbTime = sdf.format(report.get("startDate"));
String endRawDbTime = sdf.format(report.get("endDate"));
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDate startParse = LocalDate.parse(startRawDbTime,formatter);
LocalDate endParse = LocalDate.parse(endRawDbTime,formatter);
Long startTimeRaw = Long.parseLong(report.get("startDate").toString());
Instant startInst = Instant.ofEpochMilli(startTimeRaw);
ZonedDateTime zoneStart = ZonedDateTime.ofInstant(startInst, ZoneOffset.UTC);
LocalDate dateStart = formatter.format(zoneStart);
Is there a conversion step I am missing? I thought it would be simple to convert from millis to something that postgres would accept.
Worked out how to do this with PostGres by resetting the DB table to be a date with time zone, then adjusted my Java code to the following:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String startRawDbTime = sdf.format(report.get("startDate"));
String endRawDbTime = sdf.format(report.get("endDate"));
Timestamp timeStart = Timestamp.valueOf(startRawDbTime);
Timestamp timeEnd = Timestamp.valueOf(endRawDbTime);
With the statement insert updated with the right type:
reportInsert.setObject(4,timeStart, Types.TIMESTAMP);
reportInsert.setObject(5,timeEnd, Types.TIMESTAMP);
Everything works as expected now.

How to parse string with date, but without time in local format to ZonedDateTime?

This question is similar to How to parse ZonedDateTime with default zone? but addinitional condition.
I have a string param that represent a date in UK format: "3/6/09". It doesn't contain time, only date. But may contain it and even time zone.
And I want to parse it to ZonedDateTime.
public static ZonedDateTime parse(String value) {
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(SHORT).withLocale(Locale.UK).withZone(ZoneId.systemDefault());
TemporalAccessor temporalAccessor = formatter.parseBest(value, ZonedDateTime::from, LocalDateTime::from, LocalDate::from);
if (temporalAccessor instanceof ZonedDateTime) {
return ((ZonedDateTime) temporalAccessor);
}
if (temporalAccessor instanceof LocalDateTime) {
return ((LocalDateTime) temporalAccessor).atZone(ZoneId.systemDefault());
}
return ((LocalDate) temporalAccessor).atStartOfDay(ZoneId.systemDefault());
}
But, it fails with exception:
java.time.format.DateTimeParseException: Text '3/6/2009' could not be parsed at index 6
It's a bug for me, or isn't?
In my opinion is not a bug. Your approach is flawed.
First of all you are returning a ZonedDateTime so it is expected that the String contains full date, time and zone information. The string "3/6/09" should be parsed to a LocalDate.
Second, you are delegating a runtime detection of format to the library. Again, you should be parsing/formatting an expected format. Your application should know wether is expecting a full date & time or a partial (only date or only time).
Anyway you will have more luck detecting the format and then using different parsing methods.
Only local date:
DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.parse(value, LocalDate::from)`
Zoned date and time:
DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT)
.parse(value, ZonedDateTime::from)`
The format used can be seen using the getLocalizedDateTimePattern() method:
String fmt = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT, FormatStyle.SHORT, IsoChronology.INSTANCE, Locale.UK);
The result is "dd/MM/yy HH:mm".
As such, the format is expecting both a date and a time with a space separator, so that is what must be provided.
In addition, the format/parse expects there to be two digits for the day-of-month and two digits for the month-of-year. Thus, you would need to pass in "03/06/09 00:00" in order to get the result you expect, in which case you can parse directly to a LocalDateTime.
Alternatively, use ofLocalizedDate():
DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withLocale(Locale.UK);
LocalDate date = LocalDate.parse("03/06/99", formatter);
Note that the input must still have two digits for the day and month.
Alternatively, parse using a specific pattern that can handle the missing leading zeroes:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yy");
LocalDate date = LocalDate.parse("3/6/99", formatter);
LocalDate date = LocalDate.parse("03/06/99", formatter);
// handles both "3/6/99" and "03/06/99"
Update: Lenient parsing also handles this case:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseLenient().appendPattern("dd/MM/yy").toFormatter();
LocalDate date = LocalDate.parse("3/6/99", formatter);
LocalDate date = LocalDate.parse("03/06/99", formatter);
// handles both "3/6/99" and "03/06/99"

date cannot be cast to fit into JDateChooser

Hello Guys I am facing problem with casting date that I retrieve from Ms access DB to JDateChooser, but a message appear to me telling java.util.Date cannot be cast to java.util.Date..
String sql="select * from Patient where PatientID=?"; try{
ps=con.prepareStatement(sql);
ps.setString(1, txt_PID.getText());
rs=ps.executeQuery();
if(rs.next()){
// String add1=rs.getString("PatientID");
// txt_PID.setText(add1);
String add2=rs.getString("PatientName");
txt_PName.setText(add2);
String add3=rs.getString("PatientGender");
cmb_PGender.setSelectedItem(add3);
String add4=rs.getString("PatientAge");
txt_PAge.setText(add4);
String add5=rs.getString("PatientType");
cmb_PType.setSelectedItem(add5);
String add6=rs.getString("PatientGSM");
txt_PGsm.setText(add6);
String add7=rs.getString("Patient_Maj_Jop");
txt_major_Jop.setText(add7);
DateFormat formatter ;
Date date1;
String add8=rs.getString("DateOfReg");
formatter = new SimpleDateFormat("MMM d, yyyy");
date1 = (Date)formatter.parse(add8);
dch_Date.setDate(date1);
table_PatuentReg.setModel(DbUtils.resultSetToTableModel(rs));
} }catch(Exception e){ JOptionPane.showMessageDialog(null, e.getMessage());
}
if(txt_PID.getText().equals("")){
Update_Table();
}
Without looking at date1 variable, I'm guessing you might be using java.sql.Date? Check you are indeed using java.util.Date.
Show us your import statements.
The problem is with this line because DateFormatter is returning you an instance of java.util.Date and you are trying to cast it to a java.sql.Date which it isn't.
date1 = (Date)formatter.parse(add8);
Easy fix is to import java.util.Date instead. I don't see there is a need for you to use java.sql.Date as you are not fetching Date SQL colum, are you?