在有年、月、日、时、分的情况下,如何根据设备配置的日期和时间正确格式化?
当前回答
这是最简单的方法:
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对象。
这是我的方法,可以定义和输入输出格式。
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;
}
日期和时间格式说明
EEE : Day ( Mon )
MMMM : Full month name ( December ) // MMMM February
MMM : Month in words ( Dec )
MM : Month ( 12 )
dd : Day in 2 chars ( 03 )
d: Day in 1 char (3)
HH : Hours ( 12 )
mm : Minutes ( 50 )
ss : Seconds ( 34 )
yyyy: Year ( 2020 ) //both yyyy and YYYY are same
YYYY: Year ( 2020 )
zzz : GMT+05:30
a : ( AM / PM )
aa : ( AM / PM )
aaa : ( AM / PM )
aaaa : ( AM / PM )
这样就可以了:
Date date = new Date();
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));
下面是:http://developer.android.com/reference/android/text/format/Time.html
最好使用Android原生的Time类:
Time now = new Time();
now.setToNow();
然后格式:
Log.d("DEBUG", "Time "+now.format("%d.%m.%Y %H.%M.%S"));
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- 如何减去日期/时间在JavaScript?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 自定义数字格式字符串始终显示符号
- 导航目标xxx对于这个NavController是未知的