-2

I have a date-time string with time zone like "2019-05-21 04:49:39.000Z" this. How do i split the date from this string without split method.I have to use the time zone formatter. Anyone please help me in it.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • use SimpleDateFormate https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html – Jainil Patel May 24 '19 at 09:24
  • You can parse date string to Date object. From there, you can split date and time in any format using SimpleDateFormat – Ankit ihelper Sharma May 24 '19 at 09:25
  • @ Jainil Patel any example please? – Rishikesh Rahi May 24 '19 at 09:37
  • Possible duplicate of [simpledateformat parsing date with 'Z' literal](https://stackoverflow.com/questions/2580925/simpledateformat-parsing-date-with-z-literal). There are many, many similar questions. Please (always) search and go through the results you get before posting the same question again. – Ole V.V. May 25 '19 at 04:27
  • There are many ways. I would add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to my Android project (if min API level below 26), build a `DateTimeFormatter`, possibly using a `DateTimeFormatterBuilder` and a couple of predefined formatters, parse into an `OffsetDateTIme` and convert it to `LocalDate` to get only the date. – Ole V.V. May 26 '19 at 06:24

2 Answers2

2

public static String getDateTime(String created_on) {

    SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    SimpleDateFormat outFormat = new SimpleDateFormat("dd MMM yyyy hh:mm aa");

    try {

        inFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date value = inFormat.parse(created_on);

        outFormat.setTimeZone(TimeZone.getDefault());
        created_on = outFormat.format(value);

    } catch (ParseException e) {
        e.printStackTrace();
    }

    return created_on;
}

Use this Function.It will help you to get Date and Time

John
  • 65
  • 2
  • 10
1

Use some library for parsing String to e.g. OffsetDateTime, after from parsedDateTime variable get any part of the time (hour, min...) In kotlin (min API 26) :

 val parsedDateTime = OffsetDateTime
.parse("2019-05-21 04:49:39.000Z", DateTimeFormatter.ISO_DATE_TIME)
 val time = "${parsedDateTime.hour} : ${parsedDateTime.minute}"

check this link for more examples : examples

https://grokonez.com/kotlin/kotlin-convert-string-datetime

Update :
As Ole V.V. mentioned in comment - if you’re not yet on API level 26, you may add ThreeTenABP to your Android project and import OffsetDateTime from there (and than the same code works for lower API).

mr.kostua
  • 696
  • 6
  • 12
  • 1
    If you’re not yet on API level 26, you may add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project and import from `org.threeten.bp` with subpackages and then the same code works. – Ole V.V. May 25 '19 at 04:23