时间工具类之“LocalDateTime方案转换地域性时差问题->自定义时间 转 UTC时间

发布时间 2024-01-02 20:52:22作者: 骚哥

一、使用方法

1.这里有使用LocalDateTime,Date,
2.直接使用LocalDateTime来将输入时间转为UTC还是没有摸索到,看了下源码发现根据偏移量去处理的,但是没有测试成功所以换了一种方案

二、代码

测试方案

    @Test
    public void wzwLocalDateTimeTest() throws ParseException
    {

        // 将"2023-12-23"转为LocalDate格式,然后再转为LocalDateTime格式,接着调整为最小时间00:00:00,最后转换格式为"yyyy-MM-dd'T'HH:mm:ss'Z'"
        String of = LocalDateTime.of(LocalDate
                .parse("2023-12-23", DateTimeFormatter.ofPattern(SystemConstants.DATE_FORMAT_YYYY_MM_DD)),
                LocalTime.ofSecondOfDay(0)).with(LocalTime.MIN).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"));
        // of = 2023-12-23T00:00:00Z
        System.out.println("of = " + of);

        // 自定义时间 转 UTC
        String s = Utc.translatetoUtcStr(of, TimeZone.getTimeZone("UTC"), "yyyy-MM-dd'T'HH:mm:ss'Z'");
        // s = 2023-12-22T16:00:00Z
        System.out.println("s = " + s);
    }

 

时间工具类1:将输入的自定义时间【时间,zone,格式】 转为 UTC时间

/**
 * 将自定义时间 转为 UTC时间
 *
 * @author 王子威
 * @param localTime 自定义字符串时间,格式:format
 * @param localZone 时间类型【本地时间】
 * @param format 格式
 * @return
 */
public static String translatetoUtcStr(String localTime, TimeZone localZone, String format) {
    // 获取Date对象
    Date date = DateUtils.formatStrToDate(localTime, format);
    Calendar cal = Calendar.getInstance();
    // 日期
    cal.setTimeInMillis(date.getTime());
    // 设置被转换的Zone
    cal.setTimeZone(localZone);
    //首先获取一个Date对象
    Date source = cal.getTime();

    DateFormat sdf = new SimpleDateFormat(format);
    //设置转换目标UTC时区
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    // UTC.格式(传入的自定义时间)
    return sdf.format(source);
}

 

Date工具类:string转为date

/**
 * string转为date
 *
 * @param dateStr
 * @param pattern
 * @return*/
public static Date formatStrToDate(String dateStr, String pattern)
{
    SimpleDateFormat sdf = new SimpleDateFormat(pattern == null ? "yyyy-MM-dd HH:mm:ss" : pattern);
    Date date = null;
    try
    {
        date = sdf.parse(dateStr);
    }
    catch (ParseException e)
    {
        e.printStackTrace();
    }
    return date;
}

三、结果

s = 2023-12-22T16:00:00Z