package com.android.app_base.utils;
|
|
/**
|
* Created by guoshen on 2024/6/29
|
*/
|
|
import androidx.databinding.InverseMethod;
|
|
import java.text.ParseException;
|
import java.text.SimpleDateFormat;
|
import java.util.Date;
|
import java.util.Locale;
|
|
public class DateTimeConverter {
|
|
// 日期时间格式化模板
|
private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
|
// 日期格式化模板
|
private static final String DATE_FORMAT = "yyyy-MM-dd";
|
// 时间格式化模板
|
private static final String TIME_FORMAT = "HH:mm:ss";
|
|
// 将完整的日期时间字符串转换为日期部分(yyyy-MM-dd)
|
public static String dateFromString(String dateTime) {
|
if (dateTime == null || dateTime.isEmpty()) {
|
return "";
|
}
|
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_TIME_FORMAT, Locale.getDefault());
|
try {
|
Date date = dateFormat.parse(dateTime);
|
SimpleDateFormat dateFormatter = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
|
return dateFormatter.format(date);
|
} catch (ParseException e) {
|
e.printStackTrace();
|
return "";
|
}
|
}
|
|
// 将完整的日期时间字符串转换为时间部分(HH:mm:ss)
|
public static String timeFromString(String dateTime) {
|
if (dateTime == null || dateTime.isEmpty()) {
|
return "";
|
}
|
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_TIME_FORMAT, Locale.getDefault());
|
try {
|
Date date = dateFormat.parse(dateTime);
|
SimpleDateFormat timeFormatter = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault());
|
return timeFormatter.format(date);
|
} catch (ParseException e) {
|
e.printStackTrace();
|
return "";
|
}
|
}
|
|
// 反向转换:从日期和时间部分生成完整的日期时间字符串
|
@InverseMethod("dateFromString")
|
public static String stringFromDate(String date) {
|
// Not needed for this case
|
return null;
|
}
|
|
@InverseMethod("timeFromString")
|
public static String stringFromTime(String time) {
|
// Not needed for this case
|
return null;
|
}
|
}
|