Java将日期转换为不同的格式 [英] Java converting a Date to a different format

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

问题描述

我有一个这样格式的日期字符串:

  String fieldAsString =11/26/2011 14:47:31 ; 

我正在尝试将其转换为日期类型对象,格式为:yyyy。我试过使用以下代码:



<$ p



$ p> SimpleDateFormat sdf = new SimpleDateFormat(yyyy.MM.dd HH:mm:ss);
Date newFormat = sdf.parse(fieldAsString);

但是,这会抛出一个异常,它是一个不可见的日期。 / p>

所以我尝试过这样的东西:

  Date date = new SimpleDateFormat (MM / dd / yyyy HH:mm:ss)。parse(fieldAsString); 
String newFormat = new SimpleDateFormat(yyyy.MM.dd HH:mm:ss)。format(date)

但是,这种新格式现在是'String'格式,但是我希望我的函数将新的格式化日期作为'Date'对象类型返回。我该怎么做?



谢谢!

解决方案

你似乎有一种印象一个 Date 对象具有格式。没有听起来你只需要这样:

  Date date = new SimpleDateFormat(MM / dd / yyyy HH:mm:ss ).parse(fieldAsString); 

(您应该考虑指定一个区域设置和可能的时区,请记住。)



然后你有 Date 的值。当您以后想要将其转换为文本... 时,格式仅适用于您指定格式。将代表的值(在这种情况下的时间瞬间)与潜在的文本表示进行分隔很重要。这就像整数 - 这两个值之间有区别:

  int x = 0x10; 
int y = 16;

它们是相同的值,在源代码中的代码不同。



此外,请考虑在所有日期/时间工作中使用 Joda时间,这比API java.util。*


I have a date string in this format:

String fieldAsString = "11/26/2011 14:47:31";

I am trying to convert it to a Date type object in this format: "yyyy.MM.dd HH:mm:ss"

I tried using the following code:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
Date newFormat = sdf.parse(fieldAsString);

However, this throws an exception that it is an Unparsable date.

So I tried something like this:

Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(fieldAsString);
String newFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(date)

However, this new format is now in the 'String' format but I want my function to return the new formatted date as a 'Date' object type. How would I do this?

Thanks!

解决方案

You seem to be under the impression that a Date object has a format. It doesn't. It sounds like you just need this:

Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(fieldAsString);

(You should consider specifying a locale and possibly a time zone, mind you.)

Then you've got your Date value. A format is only relevant when you later want to convert it to text... that's when you should specify the format. It's important to separate the value being represent (an instant in time, in this case) from a potential textual representation. It's like integers - there's no difference between these two values:

int x = 0x10;
int y = 16;

They're the same value, just represented differently in source code.

Additionally consider using Joda Time for all your date/time work - it's a much cleaner API than java.util.*.

这篇关于Java将日期转换为不同的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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