在有年、月、日、时、分的情况下,如何根据设备配置的日期和时间正确格式化?
当前回答
这段代码将返回当前日期和时间:
public String getCurrDate()
{
String dt;
Date cal = Calendar.getInstance().getTime();
dt = cal.toLocaleString();
return dt;
}
其他回答
日期和时间格式说明
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 )
最短的方法:
// 2019-03-29 16:11
String.format("%1$tY-%<tm-%<td %<tR", Calendar.getInstance())
%tR是%tH:%tM的缩写,<表示重用最后一个参数(1$)。
它等价于String。格式(“% 1 $ tY - % 1 $ tm - td % 1 $ % 1 $ tH: % 1 $ tm”,Calendar.getInstance ())
https://developer.android.com/reference/java/util/Formatter.html
android Time类提供了3种格式化方法http://developer.android.com/reference/android/text/format/Time.html
我是这样做的:
/**
* This method will format the data from the android Time class (eg. myTime.setToNow()) into the format
* Date: dd.mm.yy Time: hh.mm.ss
*/
private String formatTime(String time)
{
String fullTime= "";
String[] sa = new String[2];
if(time.length()>1)
{
Time t = new Time(Time.getCurrentTimezone());
t.parse(time);
// or t.setToNow();
String formattedTime = t.format("%d.%m.%Y %H.%M.%S");
int x = 0;
for(String s : formattedTime.split("\\s",2))
{
System.out.println("Value = " + s);
sa[x] = s;
x++;
}
fullTime = "Date: " + sa[0] + " Time: " + sa[1];
}
else{
fullTime = "No time data";
}
return fullTime;
}
我希望这对你有帮助:-)
使用SimpleDateFormat
是这样的:
event.putExtra("starttime", "12/18/2012");
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date date = format.parse(bundle.getString("starttime"));
使用这两个作为类变量:
public java.text.DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
private Calendar mDate = null;
像这样使用它:
mDate = Calendar.getInstance();
mDate.set(year,months,day);
dateFormat.format(mDate.getTime());
推荐文章
- Android Studio, logcat在应用程序关闭后清理
- 在android中从上下文获取活动
- 无法解析主机"<URL here>"没有与主机名关联的地址
- getActivity()在Fragment函数中返回null
- 按钮背景是透明的
- 在Mac OS X上哪里安装Android SDK ?
- 我如何获得图像缩放功能?
- 在Android应用程序中显示当前时间和日期
- BottomSheetDialogFragment的圆角
- 在应用程序启动时出现“无法获得BatchedBridge,请确保您的bundle被正确打包”的错误
- 我如何改变默认对话框按钮的文本颜色在安卓5
- 更改单选按钮的圆圈颜色
- 前一个月的Python日期
- 如何在android中复制一个文件?
- adb找不到我的设备/手机(MacOS X)