Java8中java.time.*包的新日期时间类使用

  • LocalDate转String
  • String转LocalDate
  • LocalDate转Date
  • Date转LocalDate
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class Java8DateTimeTester {

    public static void main(String[] args) {
        // LocalDate -> String
        LocalDate localDate = LocalDate.now();
        System.out.println(" original:[" + localDate + "]");
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        System.out.println("formatted:[" + localDate.format(dateTimeFormatter) + "]");
        System.out.println("formatted:[" + localDate.format(DateTimeFormatter.ofPattern("y/M/d")) + "]");
        System.out.println("formatted:[" + localDate.format(DateTimeFormatter.ofPattern("yyyyMMMM")) + "]");
        System.out.println("formatted:[" + localDate.format(DateTimeFormatter.ofPattern("yy年MM月dd日星期e -1")) + "]");
        System.out.println("formatted:[" + localDate.format(DateTimeFormatter.ofPattern("yy年MM月dd日星期ee -1")) + "]");
        System.out.println("formatted:[" + localDate.format(DateTimeFormatter.ofPattern("yy年MM月dd日eee")) + "]");
        System.out.println("formatted:[" + localDate.format(DateTimeFormatter.ofPattern("yy年MM月dd日eeee")) + "]");
        System.out.println("formatted:[" + localDate.format(DateTimeFormatter.ofPattern("yy年MM月dd日星期eeeee")) + "]");
        System.out.println("  changed:[" + localDate.plusDays(60).format(dateTimeFormatter) + "]");
        System.out.println("  changed:[" + localDate.withMonth(12).format(dateTimeFormatter) + "]");
        System.out.println(" original:[" + LocalTime.now() + "]");
        System.out.println(" original:[" + LocalDateTime.now() + "]");

        System.out.println();
        // String -> LocalDate
        localDate = LocalDate.parse("2017|04|18", DateTimeFormatter.ofPattern("yyyy|MM|dd"));
        System.out.println("parsed:[" + localDate + "]");

        System.out.println();
        // LocalDate -> Date
        Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        System.out.println("dateFromLocalDate:[" + date + "]");

        System.out.println();
        // Date -> LocalDate
        localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        System.out.println("localDateFromDate:[" + localDate + "]");
    }
}

参考文章:http://www.importnew.com/14140.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值