SQLUser
SQLUser

Reputation: 97

String Date + Time to Date Object Java

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

Answers (1)

Anonymous
Anonymous

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.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Upvotes: 1

Related Questions