0

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 
ccjmne
  • 9,333
  • 3
  • 47
  • 62
  • 1
    Pls ask something when you write a question. – kai Apr 09 '14 at 09:04
  • Hi guys, i am trying to extract difference between these two timings for consecutive lines. like Result(70 ms)=(Thu Jan 16 2014 16:59:43.5090) -(Thu Jan 16 2014 16:59:43.5020) and So on..... –  Apr 09 '14 at 09:11
  • possible duplicate of [Calculating the Difference Between Two Java Date Instances](http://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances) – Oleg Estekhin Apr 09 '14 at 10:22
  • 1
    @MaduBiradar Edit the Question for clarity, rather than using a comment. Notice the "edit" link at lower-left of the Question. – Basil Bourque Apr 10 '14 at 07:40

5 Answers5

1

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

DayaMoon
  • 357
  • 2
  • 7
0

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();
sivaramaraju
  • 352
  • 2
  • 8
  • I have this code already from this website only but its not reading line by line and subtracting two consecutive lines.I am looking Like-- diff_Result=(Second_line)-(First_line); diff_Result=(Fourth_line)-(Third_line); –  Apr 09 '14 at 09:25
  • for that just store all those values in an array and construct one for loop in that intialise two variables like i=0 and j=1 and each and every time you just increment those values like - for(i=0,j=1;i – sivaramaraju Apr 09 '14 at 12:05
  • Thanks for your effort and explaination –  Apr 09 '14 at 12:40
0

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

Poomrokc The 3years
  • 1,099
  • 2
  • 10
  • 23
  • What if the number of the day is only 1 digit? – ifloop Apr 09 '14 at 09:27
  • Int do not have 02 value, it changes to 2 automatically , but I admit my code have some problem if line2 values are less than line1 values , It's the OP to choose what to use – Poomrokc The 3years Apr 09 '14 at 09:29
  • @Poomrokc, Thanks Good Effort, in my case there will not be chance to have less values in second than first.. –  Apr 09 '14 at 09:37
  • @Poomrokc, I am reading these lines from a file and i am using BufferedReader and also while((String str=buff.readLine())!=null){ what else small modification needed, i am trying but its not giving result for my file} please few help needed..appreciate your help –  Apr 09 '14 at 09:53
  • @MaduBiradar I think you got helped from DayaMoon , do you still need my help? – Poomrokc The 3years Apr 09 '14 at 10:56
  • @Poomrokc, here what i tried. i am new to java,i am student. DateFormat df = new SimpleDateFormat("EEE MMM dd yyyyHH:mm:ss.SSSS", Locale.ENGLISH); while((str=br.readLine())!=null) { String next=br.readLine(); int datedifference=Integer.parseInt(next.substring(8,10))Integer.parseInt(str.substring(8,10)); System.out.println(datediffrenece); System.out.println(df.parse(next).getTime()-df.parse(str).getTime()); –  Apr 09 '14 at 11:10
  • @ Poomrokc ,your code is correct but i am not able to put it into proper way i want i.e DATE,TIME type conversion and all those things so help needed.. –  Apr 09 '14 at 11:14
  • @all, I am getting errror like this.... Exception in thread "main" java.lang.NumberFormatException: For input string: " 1" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:569) at java.lang.Integer.parseInt(Integer.java:615) at project.Subtract.main(Subtract.java:49) Java Result: 1 –  Apr 09 '14 at 12:38
0

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

0

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?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154