繁体   English   中英

如何在android中转换日期格式

[英]how to convert date format in android

我在YYYY/MM/DD HH:MM:SS格式中将日期记录到字符串中。我想将其更改为mm/dd/yyyy HH:mm:ss ,它还会显示AM和PM我该怎么做。请帮我

谢谢

要获得AM PM和12小时日期格式,请使用hh:mm:ss a作为字符串格式化程序WHERE hh表示12小时格式, a表示AM PM格式。

注意: 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);

您可以将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();  

使用android.text.format.Time进行转换。 您可以将时间作为文本传递,它将使用timeInstance.format("")以所需格式返回时间;

你需要提供格式化程序。

请参阅以下内容:时间: http//developer.android.com/reference/android/text/format/Time.html格式化程序: http//pubs.opengroup.org/onlinepubs/007908799/xsh/strftime.html

你可以使用格式化程序字符串的任意组合来使用它:)

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

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

如果你真的需要Date对象,试试这个。

Date date = new Date(Long.parse(yourTimeString));
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") 

你可以使用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
}

暂无
暂无

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

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