Java新日期类LocalDate

package com.huawei;

import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjusters;

public class Cal {
    public static void main(String ... args) throws ParseException {
        String date_str = "2023-12-29";
        getMyCalendar(date_str);
    }
    private static void getMyCalendar(String date_str) throws ParseException {
        Instant instant = Instant.now();
        System.out.println(instant.atOffset(ZoneOffset.ofHours(8)));;

        long timestamp = Instant.now().toEpochMilli();
        System.out.println(timestamp);
        LocalDate localDate2 = Instant.ofEpochMilli(timestamp).atOffset(ZoneOffset.ofHours(8)).toLocalDate();
        System.out.println(localDate2);
        System.out.println(LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        TemporalAccessor parse = formatter.parse(date_str);
        LocalDate localDate = LocalDate.from(parse);
        //获取给定的时间是几号
        System.out.println(localDate);
        int day = localDate.getDayOfMonth();
        localDate = localDate.plusDays(-day+1);
        //将日期改为该月1号
        //获取该月1号是本周第几天
        int firstDayOfWeek = localDate.getDayOfWeek().getValue();
//            int firstDayOfWeek = localDate.with(TemporalAdjusters.firstDayOfMonth()).getDayOfWeek().getValue();
        System.out.println(firstDayOfWeek);
        System.out.println(localDate);
        //获取该月的最后一天是几号
        int lastDay = localDate.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();
        //每个月多需要6行7列即可显示完整
        int [] days = new int[6*7];
        //为数组填充值
        for(int i=1 ; i <= lastDay ; i++){
            days[firstDayOfWeek-1] = i;
            firstDayOfWeek++;
        }
        //打印日历
        System.out.println("一\t二\t三\t四\t五\t六\t日");
        for(int i = 0 ; i < days.length ; i++){
            if(days[i]!=0){
                if(days[i]==day){
                    System.out.print("*");
                }
                System.out.print(days[i]);
            }
            System.out.print("\t");
            if((i+1)%7==0){
                System.out.println("");
            }
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容