简体   繁体   English

如何从设置日期数据类型中的引用更改日期格式

[英]How to change date format from setting it reference in date data type

I am getting date in an date object 我在日期对象中获取日期

Date s = ((java.util.Date) ((Object[]) object)[++i]);

i need to set this format 20130509 06:00 我需要设置此格式20130509 06:00

so for this I have choosen .. 所以为此我选择了..

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm");
    String s1 = sdf.format(s);

now again my task is to put back in date object that string s1, please advise how to achieve this 现在我的任务是将日期对象放回字符串s1,请告知如何实现

Date doesn't have a textual format - or even a time zone or calendar. Date 没有一个文本格式-甚至时区或日历。 It's just a number of milliseconds since the unix epoch. 距unix时代只有几毫秒的时间。 There's nothing to set within Date . Date没有任何设置。

You need to differentiate between your fundamental data, and a textual representation of that data - in the same way as the int value 16 is the same as 0x10. 您需要区分基本数据和该数据的文本表示形式,就像int值16等于0x10一样。 I can't think of any time where I've found it appropriate to carry a textual representation of a date around with the date itself. 我想不出有什么合适的时间携带日期本身的文本表示形式。 In various places in your program you may well find that you need different representations for the same date - but it's usually the same representation for all dates at that specific part of the program. 在程序的各个位置,您可能会发现您需要在同一日期使用不同的表示形式,但是在该程序的特定部分, 所有日期通常是相同的表示形式。

As an aside, you should consider using Joda Time instead of java.util.Date - it provides you with a much richer set of types to consider, so you can express what your program is actually dealing with (just a date, just a time, a date/time in a particular time zone etc). 顺便说一句,您应该考虑使用Joda Time而不是java.util.Date它为您提供了更丰富的类型集,因此您可以表达程序实际处理的内容(只是一个日期,只是一个时间)。 ,特定时区中的日期/时间等)。

Ideally, you shouldn't try to translate to String format and back again. 理想情况下,您不应尝试转换为String格式并再次返回。 You should persist the original value and just use the String format for display purpose only. 您应该保留原始值,并且仅将String格式用于显示目的。

Otherwise, you can use SimpleDateFormat.parse method. 否则,您可以使用SimpleDateFormat.parse方法。

I recommend using Joda time... how given what you've got you can just do 我建议您使用Joda时间...鉴于您所拥有的,您可以做到

sdf.parse sdf.parse

@Test
public void testDateStringConversion() throws ParseException {
    Date date  = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm");
    String s1 = sdf.format(date);

    Date date2 = sdf.parse(s1);               // seconds won't match
    String s2 = sdf.format(date2);
    assertEquals(s1, s2);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM