我想在Java中获得格式化日期 [英] I want to get a formatted Date in Java

查看:97
本文介绍了我想在Java中获得格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个新的 Date 对象,其中应用了一个 SimpleDateFormat 。我想做一些例如:

I want to get a new Date object with a SimpleDateFormat applied to it. I would like to do something like:

SimpleDateFormat myFormat = new SimpleDateFormat("dd MMM yyyy kkmm");
Date today = new Date();
today = myFormat.format(today);

我不能这样做,因为今天是一个 Date 格式返回一个 String 。我也尝试过:

I can't do this, because today is a Date, and format returns a String. I also have tried:

Date today;
SimpleDateFormat myFormat = new SimpleDateFormat("dd MMM yyyy kkmm");
try{
    today = myFormat.parse((new Date()).toString());
}catch(Exception e){

}

不是一个很好的解决方案,因为当我尝试使用今天在其他地方Java抱怨说,今天可能没有被实例化。什么是更改Date对象的格式(同时保持Date对象,而不是将其转换为字符串)的好方法?

This isn't a good solution, because when I try to use today elsewhere Java complains that today may not have been instantiated. What is a good way to change the format of a Date object (while still keeping it a Date object, and not turning it to a string)?

推荐答案

您正在查看格式和日期错误。

You are looking at Format and Date wrongly.


  • 日期不包含格式。日期只是一个包含日期,月,小时,秒等日期信息的类。

  • SimpleDateFormat是告诉您Date的字符串表示形式的日期信息。但是没有关联的日期。

所以这个想法是当你必须显示日期或者必须在某个字符串中存储日期代表,你将使用SimpleDateFormat并传递你想要的字符串表示的日期。

So the idea is when you have to display date or have to store date in some string representation, you will use SimpleDateFormat and pass it the date you want string representation for.

这样做的一个好处是,我可以使用相同的Date对象,并可以显示两个不同的字符串表示(使用两个不同的SimpleDateFormat实例)。而且,反之亦然,定义了一个SimpleDateFormat实例,我可以格式化多个日期。

One benefit of doing this way is that, I can use same Date object and can show two different string representations (using two different instances of SimpleDateFormat). And also viceversa, having defined one SimpleDateFormat instance, I can format multiple dates.

编辑:

你想从日期去掉一些信息。使用

Now if you want to strip some info from the date. Use

Calendar rightNow = Calendar.getInstance();
Calendar cal = new GregorianCalendar(
   rightNow.get(YEAR),
   rightNow.get(MONTH),
   rightNow.get(DAY_OF_MONTH));
Date now = cal.getTime();

还有其他很好的帮助,如JodaTime

There are other good soln like JodaTime

参考:

GregorianCalendar
日历
Joda时间

这篇关于我想在Java中获得格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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