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很灵活吧,哈哈

  • 相关阅读:
    UVa 297 Quadtrees(树的递归)
    c++代码模板
    博客园 自定义CSS皮肤模板
    ubuntu 16.04 小键盘数字键盘开机自动启动
    set_union的几个例子
    CSU 1803 2016(数论)
    CSU 1809 Parenthesis(线段树+前缀和)
    UVA 253 Cube painting(暴力打表)
    洛谷 P1060 开心的金明
    Codeforces Round #369 (Div. 2) C. Coloring Trees(dp)
  • 原文地址:https://www.cnblogs.com/xxyfhjl/p/3974884.html
Copyright © 2011-2022 走看看