使用SimpleDateFormat问题将字符串转换为时间 [英] Converting String to Time using SimpleDateFormat issues

查看:162
本文介绍了使用SimpleDateFormat问题将字符串转换为时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在使用SimpleDateFormat将"HH:MM AA"的字符串转换为"HH:MM", 问题是我的代码在eclipse上工作正常,但是当我在Android Studio上运行它时,显示错误的输出.这是我的两个代码.

So, I'm using SimpleDateFormat to convert a String which is "HH:MM AA" to "HH:MM", The problem is my code works fine on eclipse but when I run this on Android Studio it shows wrong output. Here are my both codes.

推荐答案

问题是您将"MM"用作分钟,但应为"mm". "MM"持续了几个月.

The problem is you are using "MM" as minutes but it should be "mm". "MM" is for months.

当您希望恢复24小时值时,"HH"部分就可以了.

The part "HH" is fine when you want the 24 hour values back.

尝试这样的东西:

public static String getTimeFormatted(String time){
    String s = "";
    try{
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa", Locale.US);
        Date d = sdf.parse(time);


        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm", Locale.US);
        s = formatter.format(d);
    }
    catch(Exception ex){
        s = ex.getMessage();
    }
    return s;
}

这篇关于使用SimpleDateFormat问题将字符串转换为时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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