guoshen
2024-06-29 5325e22a184b53aadcc5e9552cb1ec54f9c8ad81
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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;
    }
}