从字符串创建Java日期,反之亦然 [英] Create a Java Date from a String and vise versa

查看:139
本文介绍了从字符串创建Java日期,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Integer format (YYYYMMDD)中有一个date.和start_time作为String (HH:mm 24小时制).和time_duration小时中作为double.

I have a date in Integer format(YYYYMMDD). And a start_time as a String (HH:mm 24 hour system). and a time_duration in hours as a double.

int date = 20140214;
String start_time = "14:30";
double duration = 50.30;

我想使用这3个值并创建2个Java Date对象.一个是start_date,另一个是end_date.它们的格式应为YYYY-MM-DD HH:mm.

I want to use these 3 values and create 2 Java Date Objects. One is start_date and one is end_date. They should be in the format YYYY-MM-DD HH:mm.

然后得到2个数据字符串,如YYYY-MM-DD HH:mm.我如何获得这些先前的变量. datestart_timeduration.

And then after I get 2 data Strings like YYYY-MM-DD HH:mm. how can I obtain those previous variables. date, start_time, duration.

这是我的尝试.

public void solve() throws IOException {
    int date = 20140214;
    String start_time = "14:30";
    double duration = 24.50;
    String startDate = "";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    startDate = getDate(date) + " " + start_time;
    try {
        Date start_Date = df.parse(startDate);
        Date end_Date = new Date(start_Date.getTime()+(int)(duration*3600*1000));
        System.out.println(df.format(start_Date));
        System.out.println(df.format(end_Date));

    } catch (ParseException ex) {

    }

}
public String getDate(int dateInt) {
    String date = "";
    String dateIntString = String.valueOf(dateInt);
    date = date + dateIntString.substring(0, 4) + "-";
    date = date + dateIntString.substring(4, 6) + "-";
    date = date + dateIntString.substring(6, 8);
    return date;
}

有没有简单的方法可以做到这一点. ?还是我可以使用的某些内置功能?

Is there any easy way to do it. ? Or some built-in capabilities I can use other than those I have used ?

推荐答案

日期时间的奇怪数据类型

使用:

  • 表示日历日期数字的int
  • 代表日期数字的字符串
  • 代表小数小时持续时间的双精度数字

...都是不寻常的方法.在处理日期时间值时,可能不是最明智的选择.

…are all unusual approaches. Probably not the wisest choices in handling date-time values.

知道绑定的类java.util.Date和.Calendar非常麻烦,应该避免.使用 Joda-Time 或新的 Java 8中.并熟悉方便的 ISO 8601 标准.

Know that the bundled classes java.util.Date and .Calendar are notoriously troublesome and should be avoided. Use either Joda-Time or the new java.time.* package (Tutorial) in Java 8. And get familiar with the handy ISO 8601 standard.

您的问题和示例忽略了时区的关键问题.在没有时区的情况下处理日期时间数据就像在不知道其字符编码的情况下处理文本文件一样.不好.

Your question and example ignore the crucial issue of time zone. Handling date-time data without time zone is like handling text files without knowing their character encoding. Not good.

使用正确的时区名称来创建时区对象.避免使用非标准的3个字母的代码.

Use proper time zone names to create time zone object. Avoid the non-standard 3-letter codes.

在Joda-Time中,DateTime对象类似于java.util.Date对象,但实际上知道其自己分配的时区.

In Joda-Time, a DateTime object is similar to a java.util.Date object but actually knows its own assigned time zone.

Joda-Time提供了三种表示时间跨度的类:周期,持续时间和时间间隔

Joda-Time offers three classes for representing spans of time: Period, Duration, and Interval.

Interval 类使用半开放式"方法,其中开头包括所有内容,结尾包括所有内容.这种方法适用于处理时间跨度和比较.寻找方便的containsabutsoverlapgap方法.

The Interval class uses the "Half-Open" approach, where the beginning is inclusive and the ending is exclusive. This approach works well for handling spans of time and comparisons. Look for the handy contains, abuts, overlap, and gap methods.

int dateInput = 20140214;
String start_timeInput = "14:30";
double durationInput = 50.30;

// Clean up these inputs.
String datePortion = Integer.toString( dateInput );
String input = datePortion + " " + start_timeInput; 
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "yyyyMMdd HH:mm");

// Specify the time zone this date-time represents.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ); // Or, DateTimeZone.UTC
DateTime dateTime = formatterInput.withZone( timeZone ).parseDateTime( input );

// Convert fractional hours to milliseconds, then milliseconds to a Duration object.
long millis = ( 60L * 60L * (long)(1000L * durationInput) ); // 1 hour = 60 minutes * 60 seconds * 1000 milliseconds.
Duration duration = new Duration( millis );

Interval interval = new Interval( dateTime, duration );

DateTimeFormatter formatterOutput = DateTimeFormat.forStyle( "MM" ).withLocale( Locale.FRANCE );
String description = "De " + formatterOutput.print( interval.getStart() ) + " à " + formatterOutput.print( interval.getEnd() );

转储到控制台...

System.out.println( "input: " + input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "duration: " + duration ); // Format: PnYnMnDTnHnMnS (from ISO 8601)
System.out.println( "interval: " + interval ); // Format: <start>/<end> (from ISO 8601)
System.out.println( "description: " + description );   

运行时...

input: 20140214 14:30
dateTime: 2014-02-14T14:30:00.000+01:00
duration: PT181080S
interval: 2014-02-14T14:30:00.000+01:00/2014-02-16T16:48:00.000+01:00
description: De 14 févr. 2014 14:30:00 à 16 févr. 2014 16:48:00

这篇关于从字符串创建Java日期,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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