简体   繁体   English

如何在android中将存储在字符串中的日期和时间转换为24格式时间?

[英]How to convert date and time stored in string to 24 format time in android?

I have my date and time stored in string ie my string contains str ="18/01/2013 5:00:00 pm". 我的日期和时间存储在字符串中,即我的字符串包含str =“18/01/2013 5:00:00 pm”。 How can I convert it to 24 format time in android? 如何在android中将其转换为24格式时间?

You can use two SimpleDateFormat instances: one to parse the input as a date and a second to format the date as a string with the desired format. 您可以使用两个SimpleDateFormat实例:一个用于将输入解析为日期,另一个用于将日期格式化为具有所需格式的字符串。

For example, formattedDate in the code below will be 18/01/2013 17:00:00 : 例如,下面代码中的formattedDate将是18/01/2013 17:00:00

String str = "18/01/2013 5:00:00 pm";
SimpleDateFormat input = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Date dt = input.parse(str);

SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String formattedDate = output.format(dt); //contains 18/01/2013 17:00:00

Notes: 笔记:

  • hh is for Hour in am/pm (1-12) whereas HH is for Hour in day (0-23). hh是上午/下午(1-12)的小时,而HH是白天的小时(0-23)。
  • for more formatting options, check the javadoc 有关更多格式选项,请检查javadoc

try 尝试

    String str ="18/01/2013 5:00:00 pm";
    Date date = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a").parse(str);
    str = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(date);
    System.out.println(str);

output 产量

18/01/2013 17:00:00

To get AM PM and 12 hour date format use hh:mm:ss a as string formatter WHERE hh is for 12 hour format and a is for AM PM format. 要获得AM PM和12小时日期格式,请使用hh:mm:ss a作为字符串格式化程序WHERE hh表示12小时格式, a表示AM PM格式。

Note: HH is for 24 hour and hh is for 12 hour date format 注意: HH为24小时,hh为12小时日期格式

SimpleDateFormat formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm:ss a");
            String newFormat = formatter.format(testDate);

Example

String date = "18/01/2013 5:00:00 pm";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/mm/dd HH:MM:SS");
        Date testDate = null;
        try {
            testDate = sdf.parse(date);
        }catch(Exception ex){
            ex.printStackTrace();
        }
        SimpleDateFormat formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm:ss a");
        String newFormat = formatter.format(testDate);
        System.out.println(".....Date..."+newFormat);

You can use SimpleDateFormat for that: 您可以使用SimpleDateFormat:

SimpleDateFormat dateFormat = new SimpleDateFormat(dd/mm/yyyy HH:mm:ss");

Refer to this which was opposite to your requirement. 请参阅该是相反的要求。 Just posted the link so you might get the idea of difference that HH and hh makes. 刚刚发布链接,这样你就可以了解HH和hh所带来的差异。

Try using the java SimpleDateFormat class. 尝试使用java SimpleDateFormat类。

Example: 例:

SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
df.parse(date);

The upper case HH use a 24h format 大写HH使用24小时格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM