user2889467
user2889467

Reputation:

Subtraction of Date and time

I am trying to subtract the date and time of two consecutive lines from a file, like doing:

String result1=line2-line1;
String result2=line4-line3;
// and so on.........

A sample file content could be the following:

 Thu Jan 16 2014 16:59:43.5020 
 Thu Jan 16 2014 16:59:43.5020 
 Thu Jan 16 2014 16:59:43.5020 
 Thu Jan 16 2014 16:59:43.5090 
 Thu Jan 16 2014 16:59:43.5100 
 Thu Jan 16 2014 16:59:43.5100 
 Thu Jan 16 2014 16:59:43.5170 
 Thu Jan 16 2014 16:59:43.9190 
 Thu Jan 16 2014 16:59:43.9200 
 Thu Jan 16 2014 16:59:43.9200 
 Thu Jan 16 2014 16:59:43.9200 
 Thu Jan 16 2014 16:59:43.9210 
 Thu Jan 16 2014 16:59:43.9210 
 Thu Jan 16 2014 16:59:43.9210 
 Thu Jan 16 2014 16:59:43.9210 
 Thu Jan 16 2014 16:59:43.9210 
 Thu Jan 16 2014 16:59:43.9220 
 Thu Jan 16 2014 16:59:43.9290 
 Thu Jan 16 2014 16:59:43.9290 
 Thu Jan 16 2014 16:59:43.9290 
 Thu Jan 16 2014 16:59:43.9330 
 Thu Jan 16 2014 16:59:44.0210 
 Thu Jan 16 2014 16:59:44.0210 
 Thu Jan 16 2014 16:59:44.0210 

Upvotes: 0

Views: 254

Answers (5)

Basil Bourque
Basil Bourque

Reputation: 338316

tl;dr

Duration.between(                               // Calculate and represent the span of time elapsed.
    LocalDateTime.parse(                        // Parse the input string as a `LocalDateTime` because it lacks any indicator of time zone or offset-from-UTC.
        "Thu Jan 16 2014 16:59:43.5020" ,       // Work with each pair of input strings.
        DateTimeFormatter.ofPattern( "EEE MMM dd uuuu HH:mm:ss.SSSS" , Locale.US )  // Define a formatting pattern to match your input. Specify human language for translation via `Locale` object.
    ) ,
    LocalDateTime.parse(
        "Thu Jan 16 2014 16:59:43.5090" , 
        DateTimeFormatter.ofPattern( "EEE MMM dd uuuu HH:mm:ss.SSSS" , Locale.US )
    ) 
)

File lines

Read your file in as a List of lines.

List< String > lines = Files.readAllLines( pathGoesHere ) ;

ISO 8601

By the way, the format used in your Question is terrible.

Whenever possible, use only standard ISO 8601 formats for serializing date-time values to text.

java.time

The modern approach uses the industry-leading java.time classes that supplanted the troublesome old legacy classes such as Date/Calendar/SimpleDateFormat.

Define a formatting pattern matching each line. Note the Locale argument specifying the human language and cultural norms to be used in translating the text.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd uuuu HH:mm:ss.SSSS" , Locale.US ) ;  // Thu Jan 16 2014 16:59:43.5020

Parse each input line as LocalDateTime because the input lacks any indicator of time zone or offset-from-UTC.

LocalDateTime ldt = LocalDateTime.parse( "Thu Jan 16 2014 16:59:43.5020" , f  );

ldt.toString(): 2014-01-16T16:59:43.502

Loop your input lines, cache each pair, and compare. Calculate and represent the span of time elapsed using Duration class.

for( int index = 0 , index < lines.size() , index + 2 ) { // Increment by two, as we are processing pairs together.
    String inputStart = lines.get( index ) ;
    LocalDateTime start = LocalDateTime.parse( inputStart , f  ) ;

    String inputStop = lines.get( index + 1 ) ;  // Move index to second of this pair of lines.
    LocalDateTime stop = LocalDateTime.parse( inputStop , f  ) ;

    // Calculate the time elapsed using generic 24-hour based days, as we lack any time zone or offset-from-UTC.
    Duration d = Duration.between( start , stop ) ; 
}

You can use that Duration object in various ways:

  • Ask for a total number of seconds, minutes, etc.
  • Ask for each part: hours and minutes and seconds and fractional second by calling the to…Part method.
  • Generate a String in standard ISO 8601 format PnYnMnDTnHnMnS where the P marks the beginning and the T separates any years-months-days from the hours-minutes-seconds.
  • Pass to the plus/minus methods found on various java.time classes.

Time zone

Be aware that the solution above is not trustworthy in that a LocalDateTime does not represent a moment, is not a point on the timeline. To determine a moment, you must place that LocalDateTime into the context of a particular time zone. Until then it has no real meaning. The Duration calculation is done using generic 24-hour days without regard for anomalies such as Daylight Saving Time (DST).

If you know for certain the time zone in which that input data was intended, apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
ZonedDateTime zdtStart = start.atZone( z ) ;

Then proceed with calculating the Duration.

Duration d = Duration.between( zdtStart , zdtStop ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Upvotes: 0

user2889467
user2889467

Reputation:

This will trim off any white spaces also...i got this here you should be very careful to mention the index of string which you would like to extract and subtract for example:

 startIndex:starts from index 0(inclusive).

 endIndex:starts from index 1(exclusive).

int datedifference=Integer.parseInt(line2.substring(8,10).trim())-Integer.parseInt(line1.substring(8,10).trim());

Upvotes: 0

DayaMoon
DayaMoon

Reputation: 367

With subtaction

DateFormat df = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss.SSSS", Locale.ENGLISH);

System.out.println( df.parse(line2).getTime() - df.parse(line1).getTime() );

Upvotes: 1

Poomrokc The 3years
Poomrokc The 3years

Reputation: 1099

Assuming you have get the context of the file. string line1 contain the text from firstline,string line2contain text from the second line.

    int datedifference=Integer.parseInt(line2.substring(8,10))-Integer.parseInt(line1.substring(8,10));
    int yeardifference=Integer.parseInt(line2.substring(11,15))-Integer.parseInt(line1.substring(11,15));
    int hourdifference=Integer.parseInt(line2.substring(16,18))-Integer.parseInt(line1.substring(16,18));
    int minutedifference=Integer.parseInt(line2.substring(19,21))-Integer.parseInt(line1.substring(19,21));
    int seconddifference=Integer.parseInt(line2.substring(22,23))-Integer.parseInt(line1.substring(22,23));
    int lastthingdifference=Integer.parseInt(line2.substring(24,28))-Integer.parseInt(line1.substring(24,28));

Then you got all int you need , just realign it the way you like

Note:For date you may have to set a logic which convert the days to int.

Cheers

Upvotes: 0

sivaramaraju
sivaramaraju

Reputation: 340

try the below code...

you can implement the basic logic as per your need

String string1 = "Oct 15, 2012 1:07:13 PM";
String string2 = "Oct 23, 2012 03:43:34 PM";
//here you want to mention the format that you want
SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy h:mm:ss a", Locale.ENGLISH);
Date date1 = sdf.parse(string1);
Date date2 = sdf.parse(string2);
//to found difference between two dates
long differenceInMillis = date2.getTime() - date1.getTime();

Upvotes: 0

Related Questions