如何从Java中的Date Object格式中删除毫秒 [英] How to remove milliseconds from Date Object format in Java

查看:603
本文介绍了如何从Java中的Date Object格式中删除毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 java.util.Date 对象将日期存储为 2014-01-24 17:33:47.214 ,但我希望日期格式为 2014-01-24 17:33:47 我想删除毫秒部分。

Since the java.util.Date object stores Date as 2014-01-24 17:33:47.214, but I want the Date format as 2014-01-24 17:33:47. I want to remove the milliseconds part.

我查了一个与我的问题相关的问题......

I checked a question related to my question...

如何删除Date对象的子秒部分

我已经尝试了给定的答案

I've tried the given answer

long time = date.getTime();
date.setTime((time / 1000) * 1000);

但我的结果日期格式为 2014-01-24 17:33:47.0 。如何从我的日期格式中删除 0 ???

but I've got my result Date format as 2014-01-24 17:33:47.0. How can I remove that 0 from my Date format???

推荐答案

基本答案是,你不能。 Date#toString 返回的值是 Date 对象的表示,它没有格式的概念,除了什么它在内部用于 toString 方法。

Basic answer is, you can't. The value returned by Date#toString is a representation of the Date object and it carries no concept of format other then what it uses internally for the toString method.

通常这不应该用于显示目的(稀有除外)场合)

Generally this shouldn't be used for display purpose (except for rare occasions)

相反,你应该使用某种 DateFormat

Instead you should be using some kind of DateFormat

例如......

Date date = new Date();
System.out.println(date);
System.out.println(DateFormat.getDateTimeInstance().format(date));
System.out.println(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(date));
System.out.println(DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(date));
System.out.println(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(date));

将输出类似......

Will output something like...

Thu Jan 30 16:29:31 EST 2014
30/01/2014 4:29:31 PM
30/01/14 4:29 PM
30/01/2014 4:29:31 PM
30 January 2014 4:29:31 PM

如果你真的陷入困境,可以使用 SimpleDateFormat ,但如果可以,我会避免这种情况,因为不是每个人都使用相同的日期/时间格式;)

If you get really stuck, you can customise it further by using a SimpleDateFormat, but I would avoid this if you can, as not everybody uses the same date/time formatting ;)

这篇关于如何从Java中的Date Object格式中删除毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆