在有年、月、日、时、分的情况下,如何根据设备配置的日期和时间正确格式化?
当前回答
避免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
推荐文章
- Android Studio, logcat在应用程序关闭后清理
- 在android中从上下文获取活动
- 无法解析主机"<URL here>"没有与主机名关联的地址
- getActivity()在Fragment函数中返回null
- 按钮背景是透明的
- 在Mac OS X上哪里安装Android SDK ?
- 我如何获得图像缩放功能?
- 在Android应用程序中显示当前时间和日期
- BottomSheetDialogFragment的圆角
- 在应用程序启动时出现“无法获得BatchedBridge,请确保您的bundle被正确打包”的错误
- 我如何改变默认对话框按钮的文本颜色在安卓5
- 更改单选按钮的圆圈颜色
- 前一个月的Python日期
- 如何在android中复制一个文件?
- adb找不到我的设备/手机(MacOS X)