Java时间戳与Date互转

1.时间戳转为日期格式字符串

 @Test
    public void test1(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 获取当前系统时间戳
        //long l = System.currentTimeMillis();
        //如果你数据库存储的时间戳类型为string,就需要将string字符串转为long类型
        String currentTime = "1602384121000";
        long l = Long.parseLong(currentTime);
        String format = sdf.format(l);
        System.out.println("日期格式:"+format);
        //输出:日期格式:2020-10-11 10:42:01
    }

2.日期格式转为时间戳

 @Test
    public void test2(){
        SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = "2020-10-11 10:42:01";
        Date date = null;
        try {
            date = sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long time1 = date.getTime();
        System.out.println("时间戳格式:"+time1);
        //输出:时间戳格式:1602384121000
    }

3.时间推迟

    @Test
    public void  test3(){
        //创建Calendar实例
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());   //设置当前时间
        //推迟一天
        //cal.add(Calendar.DATE, 1);
        //推迟一个月
       // cal.add(Calendar.MONTH, 1);
        //时间推迟一年
       cal.add(Calendar.YEAR,1);
        long time = cal.getTime().getTime();
        long time1 = new Date().getTime();

        System.out.println("当前时间戳:"+time1+";推迟一年的时间戳:"+time);
        //输出:当前时间戳:1602501173582;推迟一年的时间戳:1634037173582

    }

4.Date转String

  @Test
    public void test4(){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=new Date();
        String format = sdf.format(date);
        System.out.println("时间String:"+format);
    }
    //输出:时间String:2020-10-12 19:12:36

5.String转date

@Test
    public void  test5(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String string = "2020-10-14 10:10:00";
        Date date = null;
        try{
            date = sdf.parse(string);
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("Date:"+date);
        //输出:Date:Wed Oct 14 10:10:00 CST 2020

    }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值