在有年、月、日、时、分的情况下,如何根据设备配置的日期和时间正确格式化?
当前回答
使用Time类中的构建!
Time time = new Time();
time.set(0, 0, 17, 4, 5, 1999);
Log.i("DateTime", time.format("%d.%m.%Y %H:%M:%S"));
其他回答
在我看来,android.text.format.DateFormat. getdateformat (context)让我感到困惑,因为这个方法返回java.text.DateFormat而不是android.text.format.DateFormat - -"。
因此,我使用下面的片段代码以我的格式获取当前日期/时间。
android.text.format.DateFormat df = new android.text.format.DateFormat();
df.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());
or
android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());
此外,您还可以使用其他格式。遵循DateFormat。
避免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.
日期和时间格式说明
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 )
使用Time类中的构建!
Time time = new Time();
time.set(0, 0, 17, 4, 5, 1999);
Log.i("DateTime", time.format("%d.%m.%Y %H:%M:%S"));
这个代码为我工作!
Date d = new Date();
CharSequence s = android.text.format.DateFormat.format("MM-dd-yy hh-mm-ss",d.getTime());
Toast.makeText(this,s.toString(),Toast.LENGTH_SHORT).show();
推荐文章
- Android Studio, logcat在应用程序关闭后清理
- 在android中从上下文获取活动
- 无法解析主机"<URL here>"没有与主机名关联的地址
- getActivity()在Fragment函数中返回null
- 按钮背景是透明的
- 在Mac OS X上哪里安装Android SDK ?
- 我如何获得图像缩放功能?
- 在Android应用程序中显示当前时间和日期
- BottomSheetDialogFragment的圆角
- 在应用程序启动时出现“无法获得BatchedBridge,请确保您的bundle被正确打包”的错误
- 我如何改变默认对话框按钮的文本颜色在安卓5
- 更改单选按钮的圆圈颜色
- 前一个月的Python日期
- 如何在android中复制一个文件?
- adb找不到我的设备/手机(MacOS X)