如何在安卓中转换日期格式

12

我正在以YYYY/MM/DD HH:MM:SS格式将日期转换为字符串,我想要将它改成mm/dd/yyyy HH:mm:ss的格式,并且还要显示上午和下午的时间。请问如何做到这一点?

谢谢


我已经创建了一个简单的方法来实现这个。请参考https://dev59.com/l1sV5IYBdhLWcg3wrAZJ#40042733 - Rahul Sharma
6个回答

34

要获得上午下午和12小时的日期格式,请使用字符串格式化程序hh:mm:ss a,其中hh表示12小时制,a表示上午下午格式。

注意:HH用于24小时制,hh用于12小时制日期格式。

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

示例

String date = "2011/11/12 16:05:06";
        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);

1
很好的答案,帮了我很多..我一直在犯错 HH:mm:ss a - MKJParekh
使用hh对于12小时制也会返回0,不是吗?我点赞了这个回答。 - Si8

10
你可以使用SimpleDateFormat进行任何日期操作。
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
SimpleDateFormat DesiredFormat = new SimpleDateFormat("MM/dd/yyyy HH:MM:SS a");   
                                                             // 'a' for AM/PM

Date date = sourceFormat.parse("2012/12/31 03:20:20");
String formattedDate = DesiredFormat.format(date.getTime());  
// Now formattedDate have current date/time  
Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();  

1

1

只需使用Time类。尝试类似于这样的东西。

Time time = new Time();
time.set(Long.valueOf(yourTimeString));

如果你真的需要一个日期对象,只需尝试这个。
Date date = new Date(Long.parse(yourTimeString));

0

你可以使用SimpleDateFormat或者DateFormat,这里是示例

SimpleDateFormat gsdf = new SimpleDateFormat("YYYY/MM/DD HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a");
try{
    Date d = gsdf.parse("2011/12/13 16:17:00");
    System.out.println("new date format " + sdf.format(d));
}catch(Exception){
     // handle exception if parse time or another by cause
}

0
public static String getFormatedDate(String strDate, String sourceFormate,
        String destinyFormate) {
    SimpleDateFormat df;
    df = new SimpleDateFormat(sourceFormate);
    Date date = null;
    try {
        date = df.parse(strDate);

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

    df = new SimpleDateFormat(destinyFormate);
    return df.format(date);

}

并且像这样使用

getFormatedDate(strDate,
            "yyyy-MM-dd HH:mm:ss", "mm/dd/yyyy") 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接