如何在Android中格式化日期和时间?
16lz
2021-01-23
本文翻译自:How to format date and time in Android?
当具有年,月,日,小时和分钟时,如何根据设备配置日期和时间正确格式化?
#1楼
参考:https://stackoom.com/question/1uBf/如何在Android中格式化日期和时间
#2楼
Use these two as a class variables: 使用以下两个作为类变量:
public java.text.DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); private Calendar mDate = null;
And use it like this: 并像这样使用它:
mDate = Calendar.getInstance(); mDate.set(year,months,day); dateFormat.format(mDate.getTime());
#3楼
Use SimpleDateFormat 使用SimpleDateFormat
Like this: 像这样:
event.putExtra("starttime", "12/18/2012");SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");Date date = format.parse(bundle.getString("starttime"));
#4楼
Use build in Time class! 使用内置的Time类!
Time time = new Time();time.set(0, 0, 17, 4, 5, 1999);Log.i("DateTime", time.format("%d.%m.%Y %H:%M:%S"));
#5楼
The android Time class provides 3 formatting methods http://developer.android.com/reference/android/text/format/Time.html android时间类提供3种格式化方法http://developer.android.com/reference/android/text/format/Time.html
This is how I did it: 这是我的方法:
/*** 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;}
I hope thats helpful :-) 希望对您有所帮助:-)
#6楼
I use it like this: 我这样使用它:
public class DateUtils { static DateUtils instance; private final DateFormat dateFormat; private final DateFormat timeFormat; private DateUtils() { dateFormat = android.text.format.DateFormat.getDateFormat(MainApplication.context); timeFormat = android.text.format.DateFormat.getTimeFormat(MainApplication.context); } public static DateUtils getInstance() { if (instance == null) { instance = new DateUtils(); } return instance; } public synchronized static String formatDateTime(long timestamp) { long milliseconds = timestamp * 1000; Date dateTime = new Date(milliseconds); String date = getInstance().dateFormat.format(dateTime); String time = getInstance().timeFormat.format(dateTime); return date + " " + time; }}
更多相关文章
- Android设置全屏的方法
- No 94 · android 在规定时间内跳转到其他页面
- Android 日志工具(log)的使用方法
- Android学习笔记-ProgressBar和ListView使用方法(二)
- Android getResources().getConfiguration()方法的作用
- Android读取文件方法总结
- Android中Intent传递对象的两种方法(Serializable,Parcelable)!
- Mac安装android studio后卡在building gradle project info的解
- appium 【已解决】Android,每次启动手机中都会安装Appium setting