Android上的时间解析问题 [英] Time parsing issue on Android

查看:328
本文介绍了Android上的时间解析问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试解析时间字符串 02:22 pm 时得到一个解析异常。

I am getting a parse exception when trying to parse the time string 02:22 p.m..

I具有以下转换函数:

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;
    }

}

该方法在另一项活动中调用时间格式02:22 pm olddateformat newdateformat 是相同的: hh:mm a

The method is called in another activity with a time format "02:22 p.m.". olddateformat and newdateformat are the same: hh:mm a.

它导致日志中出现以下错误:

It causes following error in log:


java.text.ParseException :无法解释的日期:02:22 pm (偏移6)

java.text.ParseException: Unparseable date: "02:22 p.m." (at offset 6)

如何解决此问题?时间恰好是上面提到的格式。

How to resolve this issue? Time is in exactly above mentioned format.

推荐答案

我所做的改变对我来说很好。

Following changes that i've made works fine 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 你可以使用你的语言环境,英语解决了我的问题。 参考。

Locale.ENGLISH you can use your locale, english solved my issue. Reference.

感谢您的回复和参考。

Thanks for responses and references.

这篇关于Android上的时间解析问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆