Create a Java Date from a String and vise versa

北战南征 提交于 2019-12-02 17:47:23

问题


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;

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.

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.

This is my attempt.

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 ?


回答1:


Strange Data Types For Date-Time

Using:

  • An int to represent the digits of a calendar date
  • A string to represent time-of-day digits
  • A double to represent a duration of fractional hours

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

Avoid java.util.Date/Calendar

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.

Time Zone

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.

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

Joda-Time

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

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

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() );

Dump to console…

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 );   

When run…

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



回答2:


You have very many representations of date.

When in doubt, I usually head for getting to unix standard time (milliseconds since 1970) as soon as possible.

In this case it would be to convert the Integer date to a String, read out the four first as a year, two digits as month and the last two as day day, and then do the similar thing for the 24h time, and create a java.util.Date from this like so:

SimpleDateFormat dateParser=new SimpleDateFormat("yyyyMMdd HH:mm"); //please double check the syntax for this guy...
String yyyyMmDd = date.toString();
String fullDate = yyyyMmDd + " " + start_time;
java.util.Date startDate = dateParser.parse(fullDate);
long startTimeInMillis = startDate.getTime();
final long MILLISECONDS_PER_HOUR = 1000*60*60;
long durationInMillis = (long)duration*MILLISECONDS_PER_HOUR;
java.util.Date endDate = new java.util.Date(startTimeInMillis + durationInMillis);

Don't miss Joda time or Java 8 new, finally improved date handling named java.time.




回答3:


 you can write like
 int date = 20140214;
 String s=""+date;  
 Date date = new SimpleDateFormat("yyyyMMdd").parse(s);


来源:https://stackoverflow.com/questions/21952876/create-a-java-date-from-a-string-and-vise-versa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!