从Date对象中删除时间? [英] Removing time from a Date object?

查看:80
本文介绍了从Date对象中删除时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 Date 对象中删除时间。

I want to remove time from Date object.

DateFormat df;
String date;
df = new SimpleDateFormat("dd/MM/yyyy");
d = eventList.get(0).getStartDate(); // I'm getting the date using this method
date = df.format(d); // Converting date in "dd/MM/yyyy" format

但是当我转换这个日期(这是在 String 格式)它也是追加时间。

But when I'm converting this date (which is in String format) it is appending time also.

我根本不想要时间。我想要的只是21/03/2012。

I don't want time at all. What I want is simply "21/03/2012".

推荐答案

快速回答是:

不,您不允许这样做。因为这是 Date 用于。

来自的javadoc日期


类Date代表一个特定的时间,以毫秒的精度。

The class Date represents a specific instant in time, with millisecond precision.

但是,因为这个类只是一个数据对象。它不关心我们如何描述它。
当我们看到一个日期 2012/01/01 12:05:10.321 ,我们可以说它是 2012/01/01 ,这是你需要的。
有很多方法可以做到这一点。

However, since this class is simply a data object. It dose not care about how we describe it. When we see a date 2012/01/01 12:05:10.321, we can say it is 2012/01/01, this is what you need. There are many ways to do this.

示例1:通过操作字符串

输入字符串:2012/01/20 12:05:10.321

Input string : 2012/01/20 12:05:10.321

期望的输出字符串:2012/01/20

Desired output string : 2012/01/20

由于yyyy / MM / dd正是我们需要的,所以我们可以简单的操纵字符串来获得结果。

Since the yyyy/MM/dd are exactly what we need, we can simply manipulate the string to get the result.

String input = "2012/01/20 12:05:10.321";
String output = input.substring(0, 10);  // Output : 2012/01/20

示例2:通过SimpleDateFormat

输入字符串:2012/01/20 12:05:10.321

Input string : 2012/01/20 12:05:10.321

期望的输出字符串:01/20 / 2012

Desired output string : 01/20/2012

在这种情况下,我们需要一种不同的格式。

In this case we want a different format.

String input = "2012/01/20 12:05:10.321";
DateFormat inputFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = inputFormatter.parse(input);

DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date); // Output : 01/20/2012

对于 SimpleDateFormat ,请查看 SimpleDateFormat JavaDoc

这篇关于从Date对象中删除时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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