Android時間取得のDate、String、Longの3つの日付タイプ間の相互変換
dateタイプをStringタイプに変換
stringタイプをdateタイプに変換
注意:strTimeの時間フォーマットはformatTypeの時間フォーマットと同じでなければなりません.
longをDateタイプに変換
dateタイプをlongタイプに変換
longタイプをStringタイプに変換
Stringタイプをlongタイプに変換注意:strTimeの時間フォーマットとformatTypeの時間フォーマットは同じでなければなりません
// formatType yyyy-MM-dd HH:mm:ss//yyyy MM dd HH mm ss //
// data Date
public static String dateToString(Date data, String formatType) {
return new SimpleDateFormat(formatType).format(data);
}
stringタイプをdateタイプに変換
注意:strTimeの時間フォーマットはformatTypeの時間フォーマットと同じでなければなりません.
// strTime string ,
// formatType yyyy-MM-dd HH:mm:ss//yyyy MM dd HH mm ss ,
// strTime formatType
public static Date stringToDate(String strTime, String formatType)
throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat(formatType);
Date date = null;
date = formatter.parse(strTime);
return date;
}
longをDateタイプに変換
// currentTime long
// formatType yyyy-MM-dd HH:mm:ss//yyyy MM dd HH mm ss
public static Date longToDate(long currentTime, String formatType)
throws ParseException {
Date dateOld = new Date(currentTime); // long date
String sDateTime = dateToString(dateOld, formatType); // date string
Date date = stringToDate(sDateTime, formatType); // String Date
return date;
}
dateタイプをlongタイプに変換
// date date
public static long dateToLong(Date date) {
return date.getTime();
}
longタイプをStringタイプに変換
// currentTime long
// formatType string
public static String longToString(long currentTime, String formatType)
throws ParseException {
Date date = longToDate(currentTime, formatType); // long Date
String strTime = dateToString(date, formatType); // date String
return strTime;
}
Stringタイプをlongタイプに変換注意:strTimeの時間フォーマットとformatTypeの時間フォーマットは同じでなければなりません
// strTime String
// formatType
// strTime formatType
public static long stringToLong(String strTime, String formatType)
throws ParseException {
Date date = stringToDate(strTime, formatType); // String date
if (date == null) {
return 0;
} else {
long currentTime = dateToLong(date); // date long
return currentTime;
}
}