zoukankan      html  css  js  c++  java
  • 日期类的使用(java)蓝桥杯

    蓝桥杯日期问题常考,java提供了日期类很方便;

    //日历类

    Calendar c = Calendar.getInstance();  // 获取实例化对象

    Date date =c.getTime();      // 日期类得到c的时间;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");  // 修改格式
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-mm-dd");  
    String now =sdf.format(date);  //  以字符串方式得到时间,用sdf修改date得到自己希望的格式
    System.out.println(now);  // 输出当前时间/日期

    使用日历类根据日期得到星期:

    Calendar calendar = Calendar.getInstance();
    //2017年12月29日:星期五
    calendar.set(2017 , 11, 29); //注意月份是用0-11代表1-12月
    int a = calendar.get(Calendar.DAY_OF_WEEK);
    System.out.println(a);//1-7代表星期日-星期六

    例题:

    从键盘输入一个日期,格式为yyyy-M-d

    要求计算该日期与1949年10月1日距离多少天

    例如:

    用户输入了:1949-10-2 程序输出:1

    用户输入了:1949-11-1 程序输出:31

    代码:

    public class Demo1 {
        static long sum = 0;
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String next = sc.next();
            String[] s = next.split("-");// 以 - 为分界拆分为字符串数组
            int year = Integer.parseInt(s[0]);
            int month = Integer.parseInt(s[1]);
            int day = Integer.parseInt(s[2]);
            // 日期类
            // 取得两个到元年的时间相减变成天数
            Date d1 = new Date(year, month, day);
            long t1 = d1.getTime();// 返回的是毫秒值
            Date d2 = new Date(1949, 10, 1);
            long t2 = d2.getTime();
            long sum = (t1 - t2) / (1000 * 60 * 60 * 24) + 1; // 转化为天数
            System.out.println(sum);
    
        }
    
    }

    错误或者不足的地方欢迎指正!!

     最后分享一个喜欢的句子:

      风雪中,羊走得很慢,人也走得很慢。牧羊人的皮帽子湿漉漉的,他无精打采的把脑袋缩在翻起来的皮袄领子里。羊摇头晃脑,没什么目的。牧羊人低垂着脑袋,仿佛也没什么目的。他们出现得过于不合时宜了,只是在这世间到处走,就耗尽了他们的力气。 
  • 相关阅读:
    阿里云OSS学习
    spring学习(十二)--spring中WebApplicationInitializer解析
    spring学习(十)--WebApplicationInitializer接口替代web.xml启动spring容器
    tomcat学习(二)--tomcat配置详解
    tomcat学习(一)--tomcat请求过程
    WEB工程中web.xml文件基本配置
    MAVEN学习(九)--利用nexus创建私服供上传下载jar包
    NGINX学习(九)--nginx配置示例
    Django所有ORM总结
    ORM一般操作
  • 原文地址:https://www.cnblogs.com/yang4869/p/8127535.html
Copyright © 2011-2022 走看看