在有年、月、日、时、分的情况下,如何根据设备配置的日期和时间正确格式化?


当前回答

避免j.u.Date

Java(和Android)中的Java.util. date和. calendar和SimpleDateFormat是出了名的麻烦。避免它们。它们太糟糕了,以至于Sun/Oracle放弃了它们,用新的java取代了它们。Java 8中的time包(2014年Android中没有)。新的java。time的灵感来自Joda-Time图书馆。

乔达时间

Joda-Time在Android上运行。

在StackOverflow上搜索“Joda”可以找到很多例子和很多讨论。

使用Joda-Time 2.4的一小段源代码。

标准格式。

String output = DateTime.now().toString(); 
// Current date-time in user's default time zone with a String representation formatted to the ISO 8601 standard.

本地化的格式。

String output = DateTimeFormat.forStyle( "FF" ).print( DateTime.now() ); 
// Full (long) format localized for this user's language and culture.

其他回答

这是最简单的方法:

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.US);

    String time = df.format(new Date());

如果你在寻找模式,检查这个 https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

使用标准的Java DateFormat类。

例如,要显示当前的日期和时间,请执行以下操作:

Date date = new Date(location.getTime());
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));

你可以用你自己的值初始化一个Date对象,但是你应该知道构造函数已经被弃用了,你应该真正使用一个Java Calendar对象。

Date to Locale日期字符串:

Date date = new Date();
String stringDate = DateFormat.getDateTimeInstance().format(date);

选项:

   DateFormat.getDateInstance() 

- > 1969年12月31日

   DateFormat.getDateTimeInstance() 

-> 1969年12月31日下午4:00:00

   DateFormat.getTimeInstance() 

->下午4:00:00

这是我的方法,可以定义和输入输出格式。

public static String formattedDateFromString(String inputFormat, String outputFormat, String inputDate){
    if(inputFormat.equals("")){ // if inputFormat = "", set a default input format.
        inputFormat = "yyyy-MM-dd hh:mm:ss";
    }
    if(outputFormat.equals("")){
        outputFormat = "EEEE d 'de' MMMM 'del' yyyy"; // if inputFormat = "", set a default output format.
    }
    Date parsed = null;
    String outputDate = "";

    SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, java.util.Locale.getDefault());
    SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, java.util.Locale.getDefault());

    // You can set a different Locale, This example set a locale of Country Mexico.
    //SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, new Locale("es", "MX"));
    //SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, new Locale("es", "MX"));

    try {
        parsed = df_input.parse(inputDate);
        outputDate = df_output.format(parsed);
    } catch (Exception e) { 
        Log.e("formattedDateFromString", "Exception in formateDateFromstring(): " + e.getMessage());
    }
    return outputDate;

}

现在已经太迟了,但它可能对某人有所帮助

DateFormat.format(format, timeInMillis);

这里是你需要的格式

"HH:mm"返回15:30