java 凌晨时间戳,在Java中格式化时间戳

I wish to produce a current timestamp in the format of yyyy-MM-dd HH:mm:ss. I have written up the following code, but it always gives me this format yyyy-MM-dd HH:mm:ss.x

How do you get rid of the .x part ?

DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String currentTime = df.format(new Date());

Timestamp timestamp = Timestamp.valueOf(currentTime);

I need to have a timestamp type for writing into mysql.

解决方案

Probably you're looking at the String representation the Timestamp object gives in your database engine or its Java representation by printing it in the console using System.out.println or by another method. Note that which is really stored (in both Java side or in your database engine) is a number that represents the time since epoch (usually January 1st 1970) and the date you want/need to store.

You should not pay attention to the String format it is represented when you consume your Timestamp. This can be easily demostrated if you apply the same SimpleDateFormat to get a String representation of your timestamp object:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String currentTime = df.format(new Date());

Timestamp timestamp = Timestamp.valueOf(currentTime)

//will print without showing the .x part

String currentTimeFromTimestamp = df.format(currentTime);

Anyway, if you want the current time, just create the Timestamp directly from the result of new Date:

Timestamp timestamp = new Timestamp(new Date().getTime());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值