Reputation: 97
I am trying to convert a string "8/2/2018 04:25 AM"
into a date object
but it seems to be converting it wrong making it output a completely wrong date
and time
when I do a date.toString()
. Note - I do not care about the date.toString()
format, I just need it to be the same date and time
Here is my code,
String timestampString = dateText.getText().toString() + " " + timeText.getText().toString();
try {
Date timestamp2 = new SimpleDateFormat("dd/MM/yyyy hh:mm a").parse(timestampString);
Log.d("TIME", timestamp2.toString());
} catch (ParseException e) {Log.d("TAG", e)}
Here is the output:
D/TIME: Wed Feb 07 23:25:00 EST 2018
if anyone could lead me in the right direction, it is greatly appreciated.
Upvotes: 0
Views: 163
Reputation: 86324
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/uuuu");
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
LocalDate date = LocalDate.parse(dateText.getText(), dateFormatter);
LocalTime time = LocalTime.parse(timeText.getText(), timeFormatter);
LocalDateTime dateTime = date.atTime(time);
Log.d("TIME", dateTime.toString());
Prints:
D/TIME: 2018-02-08T04:25
I am using and recommending java.time
, the modern Java date and time API.The Date
class that you were using is long outdated, SimpleDateFormat
is too and also notoriously troublesome. Avoid those if you can. java.time
is so much nicer to work with. And offers the LocalXx
classes that don’t have time zones, which guarantees to guard you against time zone issues. That said, you may want to convert your date-time into a ZonedDateTime
in a time zone of your choice to make it an unambiguous point in time.
Yes, java.time
works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Upvotes: 1