zoukankan      html  css  js  c++  java
  • java SimpleDateFormat日期与时间戳的相互转换

    自我总结,有什么不到位的地方,各位可以帮忙纠正补充一下,感激不尽!

    目的:SimpleDateFormat类可以很随意的组合日期时间的格式,不止单纯的yyyy-MM-dd这种格式

    废话不多说,上代码

    测试类 DateTest

    package com.core.test;
    
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class DateTest {
    
        public static void main(String[] args) throws ParseException {
            SimpleDateFormat sdf0 = new SimpleDateFormat("yyyyMMdd");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
            SimpleDateFormat sdf3 = new SimpleDateFormat("ddMMyyyy");
    
            String time0 = "20140916";
            String time1 = "2014-09-16";
            String time2 = "2014年09月16日";
            String time3 = "16092014";
    
            convertStamp(sdf0, time0);
            convertStamp(sdf1, time1);
            convertStamp(sdf2, time2);
            convertStamp(sdf3, time3);
    
            long stamp = 1410796800000L;
            convertDate(sdf0, stamp);
            convertDate(sdf1, stamp);
            convertDate(sdf2, stamp);
            convertDate(sdf3, stamp);
        }
    
        // 日期转换成时间戳
        public static void convertStamp(SimpleDateFormat format, String time)throws ParseException {
            Date date = format.parse(time);
            System.out.println(date.getTime());
        }
    
        // 时间戳转换成日期
        public static void convertDate(SimpleDateFormat sdf, long stamp) {
            String date = sdf.format(new Date(stamp));
            System.out.println(date);
        }
    
    }

    运行结果:

    1410796800000
    1410796800000
    1410796800000
    1410796800000
    20140916
    2014-09-16
    2014年09月16日
    16092014

    SimpleDateFormat很灵活吧,哈哈

  • 相关阅读:
    总结Spring Set注入方式及对property标签的理解
    spring基于Annotation装配Bean时在bean.xml中添加<context:component-scan>标签报错
    java web(struts2)+python+mysql 的简单实践
    罗辑思维--怎样成为一个高手
    教练助手
    小组作业(第五组)
    个人开发总结
    第五组小组作业
    个人作业
    小组总结
  • 原文地址:https://www.cnblogs.com/xxyfhjl/p/3974884.html
Copyright © 2011-2022 走看看