本文翻译自:How to format date and time in Android?
当具有年,月,日,小时和分钟时,如何根据设备配置日期和时间正确格式化?
参考:https://stackoom.com/question/1uBf/如何在Android中格式化日期和时间
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());
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"));
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"));
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 :-) 希望对您有所帮助:-)
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;
}
}