时间格式转换&&时间戳

本文介绍了Java中时间戳与时间格式转换的相关知识。时间戳在数据库操作中常用于防止脏读,例如使用java.sql.Timestamp。讨论了Date类型的精度以及获取时间戳的方法,如System.currentTimeMillis()。同时提到了时间格式化,使用SimpleDateFormat进行日期转换,并指出在获取时间戳时,避免使用Calendar.getInstance().getTimeInMillis(),因其涉及时区处理,效率较低。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • Date精确度<时间戳
  • 时间戳Timestamp是一种时间存储类型
  • 主要用于数据库,在java.sql包内,通常用来防止数据出现脏读现象 。
时间

附:

SimpleDateFormat parser = new SimpleDateFormat(“EEEE, MMMM dd, yyyy”);
SimpleDateFormat formatter = new SimpleDateFormat(“EEE. MM/dd”);

SimpleDateFormat  sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//SimpleDateFormat sdf= new SimpleDateFormat("yyyy 年 MM 月 dd 日 HH 时 mm 分 ss 秒");
Date date = new Date();
String dateString = sdf.format(date);

在这里插入图片描述
格式化的时间转为date
附:需要把代码异常抛出

try {
            String a = "2020-07-21 18:09:12";
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date =  format.parse(a);
            System.out.println(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
时间戳
  • System.currentTimeMillis();
  • Calendar.getInstance().getTimeInMillis();
  • new Date().getTime();
    在这里插入图片描述

获取时间戳尽量不要使用中间那一种,因为它需要处理时区问题,进行时间计算,耗时会久一些。

时间戳与时间格式转换
  • 时间戳转时间
 long timestamp=new Date().getTime();    //时间戳
 SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置格式
 // SimpleDateFormat format = new SimpleDateFormat("yyyy 年 MM 月 dd 日 HH 时 mm 分 ss 秒");
 //转换1:
 String timeText=format.format(timestamp);
 //转换2:
  String sd2 = sdf2.format(new Date(Long.parseLong(String.valueOf(timestamp))));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值