Android parsing time

I get a parsing exception when trying to parse a time string 02:22 p.m..

I have the following conversion function:

public static long convertdatetotimestamp(String datestring, String newdateformat, String olddateformat){
    SimpleDateFormat originalFormat = new SimpleDateFormat(olddateformat,Locale.ROOT);
    SimpleDateFormat targetFormat = new SimpleDateFormat(newdateformat,Locale.ROOT);
    Date date = null;
    try {
        date = originalFormat.parse(datestring);
        String formattedDate = targetFormat.format(date);
        Date parsedDate = targetFormat.parse(formattedDate);
        long nowMilliseconds = parsedDate.getTime();

        return nowMilliseconds;
    } catch (ParseException e) {
        e.printStackTrace();
        return 0;
    }

}

The method is called in another action with a temporary format "02:22 p.m.". olddateformatand newdateformatthe same: hh:mm a.

This causes the following error in the log:

java.text.ParseException: Unsurpassed date: "02:22 pm". (at offset 6)

How to solve this problem? The time is in the above format.

+4
source share
3 answers

The following changes I made are great for me.

 public static long convertdatetotimestamp(String datestring, String newdateformat, String olddateformat){
        DateFormat originalFormat = new SimpleDateFormat(olddateformat,Locale.ENGLISH);
        DateFormat targetFormat = new
                SimpleDateFormat(newdateformat,Locale.ENGLISH);
        Date date = null;
        try {
            date = originalFormat.parse(datestring.replaceAll("\\.", ""));
            String formattedDate = targetFormat.format(date);
            Date parsedDate = targetFormat.parse(formattedDate);
            long nowMilliseconds = parsedDate.getTime();

            return nowMilliseconds;
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }

    }

Locale.ENGLISH, , . .

.

0

, . .. . , Java 8. , Android, .

String datestring = "02:22 p.m.";
Locale parseLocale = Locale.forLanguageTag("ga");
DateTimeFormatter originalFormat = DateTimeFormatter.ofPattern("hh:mm a", parseLocale);
System.out.println(LocalTime.parse(datestring, originalFormat));

14:22

, Java API , ThreeTenABP. . ThreeTenABP Android. , SimpleDateFormat.

US Spanish locale Java 8, : Locale.forLanguageTag("es-US").

+3

, SimpleDateFormat p.m. ( AM PM).

, - :

String time = "02:22 p.m.";
SimpleDateFormat format = new SimpleDateFormat("hh:mm a", Locale.ROOT);
date = format.parse(time.replaceAll("\\.", ""));

: nowMilliseconds (//) . String, SimpleDateFormat 1 st 1970 ( ) .

, , 1970 , Java, , /, . , , , .

, (America/Sao_Paulo), - 62520000. (, Asia/Kolkata), 31920000. , .

, olddateformat newdateformat , 2 .


API / Java

(Date, Calendar SimpleDateFormat) , API.

Android ThreeTen Backport, backport Java 8 . ThreeTenABP ( , ).

org.threeten.bp.

API , AM/PM, org.threeten.bp.format.DateTimeFormatterBuilder ( ). - ( ), org.threeten.bp.LocalTime ( -///nanosecond - ):

String time = "02:22 p.m.";
// map AM and PM values to strings "a.m." and "p.m."
Map<Long, String> map = new HashMap<Long, String>();
map.put(0L, "a.m.");
map.put(1L, "p.m.");
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
    // hour and minute
    .appendPattern("hh:mm ")
    // use custom values for AM/PM
    .appendText(ChronoField.AMPM_OF_DAY, map)
    // create formatter
    .toFormatter(Locale.ROOT);

// parse the time
LocalTime parsedTime = LocalTime.parse(time, fmt);

parsedTime , 02:22 PM ( , (//), ).

( 1970-01-01T00:00Z), (//) . , .

API SimpleDateFormat "" ( 1 st 1970 ), API , , .

Asia/Kolkata, ( ):

import org.threeten.bp.LocalDate;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZonedDateTime;

// timezone for Asia/Kolkata
ZoneId zone = ZoneId.of("Asia/Kolkata");
// current date in Kolkata timezone
LocalDate now = LocalDate.now(zone);
// get the parsed time at the specified date, at the specified zone
ZonedDateTime zdt = parsedTime.atDate(now).atZone(zone);
// get the millis value
long millis = zdt.toInstant().toEpochMilli();

, LocalDate.of(2017, 5, 20) - , , 20 th 2017. .

, API IANA ( Region/City, America/Sao_Paulo Asia/Kolkata). (, IST PST), .

( , ), ZoneId.getAvailableZoneIds().


, SimpleDateFormat, LocalDate.of(1970, 1, 1) ZoneId.systemDefault() - , , , .

, ( org.threeten.bp.temporal.ChronoField) . , org.threeten.bp.Instant millis:

String time = "02:22 p.m.";
ZoneId zone = ZoneId.of("Asia/Kolkata");
DateTimeFormatter fmt2 = new DateTimeFormatterBuilder()
    // hour and minute
    .appendPattern("hh:mm ")
    // use custom values for AM/PM (use the same map from previous example)
    .appendText(ChronoField.AMPM_OF_DAY, map)
    // default value for day: 1
    .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
    // default value for month: January
    .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
    // default value for year: 1970
    .parseDefaulting(ChronoField.YEAR, 1970)
    // create formatter at my specific timezone
    .toFormatter(Locale.ROOT).withZone(zone);
// get the millis value
long millis = Instant.from(fmt2.parse(time)).toEpochMilli();
+2

Source: https://habr.com/ru/post/1681961/


All Articles