0

I want to transfer this "2020-05-29T11:40:55Z" to Date or Calender, if i transfer it directly, like Date("2020-05-29T11:40:55Z"), An error would be throw out. Anyone has ideas? What's more, My min Android Api is 19, So plenty of api for Java 8 and Api26 is prohibited.

Cyrus
  • 8,995
  • 9
  • 31
  • 58
  • please use **joda time API**. [This](https://stackoverflow.com/questions/6252678/converting-a-date-string-to-a-datetime-object-using-joda-time-library) question will help. –  Jun 04 '20 at 08:24
  • first convert it to some other standard format and transfer ... – AgentP Jun 04 '20 at 08:29
  • @Mandy8055 Joda-Time has been obsolete for several years. – chrylis -cautiouslyoptimistic- Jun 04 '20 at 08:30
  • 1
    @chrylis-cautiouslyoptimistic- it's not obsolete. It is migrated on java 1.8 `time package`. Please read citations [**here.**](http://www.joda.org/joda-time/) and if something is obsolete i.e. `java.util.Date` –  Jun 04 '20 at 08:32
  • 2
    If you can, avoid `Date`, `Calendar` and `SimpleDateFormat`. Use `OffsetDateTime` from the `java.time` package instead. It would then be as simple as `OffsetDateTime.parse("2020-05-29T11:40:55Z")`. – MC Emperor Jun 04 '20 at 08:39
  • 2
    If you are targeting Android API levels lower that 26, you could use the ThreeTen Android Backport. More details [here](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – MC Emperor Jun 04 '20 at 08:41
  • @MCEmperor yes, my min Api is 19 – Cyrus Jun 04 '20 at 08:43

1 Answers1

2

I didn't quite understand the last part of your question. Are you saying that you cannot use java 8 in your project ? .For java 8 based , use ZonedDateTime like :

//1 - default pattern
String timeStamp = "2019-03-27T10:15:30";
ZonedDateTime localTimeObj = ZonedDateTime.parse(time);

//2 - specified pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a z");
String timeStamp1 = "2019-03-27 10:15:30 AM";
ZonedDateTime localTimeObj1 = ZonedDateTime.parse(timeStamp1, formatter);

//To get LocalDate from ZonedDateTime
LocalDate localDate = localTimeObj1.toLocalDate();

Using the old way to get the date :

    String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss a";
    SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);

    TimeZone tzInAmerica = TimeZone.getTimeZone("America/New_York");
    formatter.setTimeZone(tzInAmerica);

    String sDateInAmerica = formatter.format("2019-03-27 10:15:30 AM"); 
    //Create another simpledateformatter with your required format and use it to convert
    SimpleDateFormat formatter2 = new SimpleDateFormat(REQUIRED_DATE_FORMAT);
    Date date = formatter2.parse(sDateInAmerica);
Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39