zoukankan      html  css  js  c++  java
  • SimpleDateFormat日期和文本之间相互转换

               java.text.DateFormat 是日期/时间格式化子类的抽象类,我们可以通过他的子类SimpleDateFormat在Date对象与String对象之间进行来回转换

    格式化:按照指定的格式,从Date对象转换为String对象。

    解析:按照指定的格式,从String对象转换为Date

    DateFormat类的常用方法有:
    public String format(Date date) :将Date对象格式化为字符串。
    public Date parse(String source) :将字符串解析为Date对象。

    把Date对象转换成String

    使用format方法的代码为:


    public class Demo03 {
    public static void main(String[] args) {
      Date date = new Date();
    // 创建日期格式化对象,在获取格式化对象时可以指定风格
    DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
    String str = df.format(date);
    System.out.println(str); // 2008年1月23日
    }
    }

    把String对象转换成Date

    使用parse方法的代码为:

    public class Demo04 {
    public static void main(String[] args) throws ParseException {
    DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
    String str = "2018年12月11日";
    Date date = df.parse(str);
    System.out.println(date); // Tue Dec 11 00:00:00 CST 2018
    }
    }

  • 相关阅读:
    [CF997E] Good SubSegment
    CF916E
    BZOJ2006 超级钢琴
    BZOJ4571
    凸包总结
    树形DP入门
    bzoj4300 绝世好题(位运算+DP)
    bzoj4552 [Tjoi2016&Heoi2016]排序 (线段树+二分)
    SP1716 GSS3
    Noip2009 Hankson 的趣味题 (简单数学)
  • 原文地址:https://www.cnblogs.com/zhangxiaozhen/p/10544868.html
Copyright © 2011-2022 走看看