Java时间转换工具类

记录使用过的一些时间转换工具类
主要包括

  • String 转LocalDateTime
  • LocalDateTime 转 String
  • Date 转 LocalDateTime
  • LocalDateTime 转 Date
  • String 转 Date
  • Date 转String
public class LocalDateTimeUtil {

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static String LoaclDateTimeToStr(LocalDateTime localDateTime) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return df.format(localDateTime);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static LocalDateTime StrToLoaclDateTime(String time) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String str = "";
        for(int i = 0;i < time.length();i++){
            if(time.charAt(i) == 'T'){
                str += ' ';
            }else{
                str += time.charAt(i);
            }
        }
        return LocalDateTime.parse(str,df);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static LocalDateTime DateToLocalDateTime(Date date) throws ParseException {
        Log.e("datetolocalDatetime",date.toString());
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();

        // atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
        LocalDateTime localDate = instant.atZone(zoneId).toLocalDateTime();
        Log.e("localdateTime",localDate.toString());

        return localDate;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static Date LocalDateTimeToDate(LocalDateTime localDateTime) {
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate localDate = LocalDate.now();
        ZonedDateTime zdt = localDate.atStartOfDay(zoneId);

        Date date = Date.from(zdt.toInstant());
        return date;
    }

    public static Date StrToDate(String s) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = simpleDateFormat.parse(s);
        return date;
    }

    public static String DateToStr(Date date) {

        String str = date.toString();
        Log.e("datetostring",date.toString());
        String res = "";
        for(int i = 0;i < str.length();i++) {
            if(str.charAt(i) == 'T'){
                res += ' ';
            }else {
                res += str.charAt(i);
            }
        }
        return res;
    }

    public static String getDate() {
        Date date =new Date();
        System.out.println(date);

        //Date类型转String  //可指定任意的返回格式  yyyy
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = sdf.format(date);
        return dateString;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值