zoukankan      html  css  js  c++  java
  • DateFormat类和SimpleDateFormat类

    ·DateFormat类的作用

         把时间对象转化成指定格式的字符串。反之,把指定格式的字符串转化成时间对象。

         DateFormat是一个抽象类,一般使用它的的子类SimpleDateFormat类来实现。

    【示例】DateFormat类和SimpleDateFormat类的使用

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class TestDateFormat {
        public static void main(String[] args) throws ParseException {
            // new出SimpleDateFormat对象
            SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            SimpleDateFormat s2 = new SimpleDateFormat("yyyy-MM-dd");
            // 将时间对象转换成字符串
            String daytime = s1.format(new Date());
            System.out.println(daytime);
            System.out.println(s2.format(new Date()));
            System.out.println(new SimpleDateFormat("hh:mm:ss").format(new Date()));
            // 将符合指定格式的字符串转成成时间对象.字符串格式需要和指定格式一致。
            String time = "2007-10-7";
            Date date = s2.parse(time);
            System.out.println("date1: " + date);
            time = "2007-10-7 20:15:30";
            date = s1.parse(time);
            System.out.println("date2: " + date);
        }
    }

         执行结果如图所示:

    图8-16 示例8-15运行效果图.png

         代码中的格式化字符的具体含义见表:

    表8-2 格式化字符的含义.png

         时间格式字符也可以为我们提供其他的便利。比如:获得当前时间是今年的第几天。代码如下:

    【示例】时间格式字符的使用

    1
    2
    3
    4
    5
    6
    7
    8
    9
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class TestDateFormat2 {
        public static void main(String[] args) {
            SimpleDateFormat s1 = new SimpleDateFormat("D");
            String daytime = s1.format(new Date());
            System.out.println(daytime);
        }
    }

         执行结果如图所示:

    图8-17 示例8-16运行效果图.png

  • 相关阅读:
    tp5最强分页 自定义model,控制器引用。只显示一页
    tp5分页,一看就懂,简单明了(附带额外参数)
    PHP 验证5-20位数字加字母的正则(数字和字母缺一不可)!!!
    表格样式
    tp5中很牛皮的一句sql语句,三个条件(两个不确定条件,一个硬性条件)
    centos6.8下搭建git和gitlab版本库
    解决 nginx: [alert] kill(1022, 1) failed (3: No such process)
    Zabbix利用msmtp+mutt发送邮件报警
    nginx基本配置与参数说明
    Linux添加/删除用户和用户组
  • 原文地址:https://www.cnblogs.com/huaxiansheng/p/15316124.html
Copyright © 2011-2022 走看看