简体   繁体   中英

Extract timestamp from the middle of a line in text file

I am trying to read one text file which contains different information. One part of the text file contains the below information that I needed

### Size: 280
### file data: 
### Scenario: - timestamp: 1620832134319 - Wed May 12 17:08:54 CEST 2021
### It needed to compare later timestamp: 1620832134319 - Wed May 12 17:08:54 CEST 2021

I am trying to extract this timestamp "1620832134319" or "Wed May 12 17:08:54". Then I need to add 10 days in the future. and compare the original timestamp and timestamp 10 days in the future more if they are the same or not.

Can someone please help me or guide me in this scenario. Until now I tried to open the file but reading and extracting that timestamp and adding more parts is where I am really stuck.

public class readTimeStampTest
{

static String filePath = "c:/timestamp.txt";
long timestamp10daysinfuture = 1621868934;

public static void getTimeStamp()
{
    System.out.println("timestamp test... " );
    File file = new File(filePath);
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    String line;
    while((line = br.readLine()) != null){
        //process the line
        System.out.println(line);

   1st step:  Extract timestamp 

   2nd step: Compare original and future timestamp (timestamp10daysinfuture )


   }     }

I tried to look in SO for extracting the timestamp first, but that timestamp is in a different format as mentioned in the below link. because normally the timestamp is at the start of the text file, but here it is in middle and I think it needs regex.

How to Read Time and Date from Text File in Java 5?

Any help would be greatly appreciated.

You can use the regex, (?<=timestamp:\h)\d+(?=\h-) to retrive the match.

With Java-11:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) throws IOException {
        System.out.println(getTimeStamp("myfile.txt"));
    }

    static String getTimeStamp(String filePath) throws IOException {
        return Pattern.compile("(?<=timestamp:\\h)\\d+(?=\\h-)")
                    .matcher(Files.readString(Path.of(filePath), StandardCharsets.US_ASCII))
                    .results()
                    .map(MatchResult::group)
                    .findAny()
                    .orElse("");
    }
}

Output:

1620832134319

With Java-9:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) throws IOException {
        System.out.println(getTimeStamp("myfile.txt"));
    }

    static String getTimeStamp(String filePath) throws IOException {
        String str = Files.lines(Paths.get(filePath), StandardCharsets.US_ASCII).collect(Collectors.joining());
        return Pattern.compile("(?<=timestamp:\\h)\\d+(?=\\h-)")
                    .matcher(str)
                    .results()
                    .map(MatchResult::group)
                    .findAny()
                    .orElse("");
    }
}

With Java-8:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) throws IOException {
        System.out.println(getTimeStamp("myfile.txt"));
    }

    static String getTimeStamp(String filePath) throws IOException {
        String str = Files.lines(Paths.get(filePath), StandardCharsets.US_ASCII).collect(Collectors.joining());
        Matcher matcher = Pattern.compile("(?<=timestamp:\\h)\\d+(?=\\h-)").matcher(str);
        if (matcher.find()) {
            return matcher.group();
        } else {
            return "";
        }
    }
}

Explanation of the regex at regex101 :

Positive Lookbehind (?<=timestamp:\h)
    Assert that the Regex below matches
    timestamp: matches the characters timestamp: literally (case sensitive)
    \h matches any horizontal whitespace character (equivalent to [[:blank:]])
\d matches a digit (equivalent to [0-9])
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
Positive Lookahead (?=\h-)
    Assert that the Regex below matches
    \h matches any horizontal whitespace character (equivalent to [[:blank:]])
    - matches the character - literally (case sensitive)

A demo of how to process the retrieved timestamp:

import java.io.IOException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws IOException {
        String timestamp = "1620832134319";

        // Change the ZoneId as per your requirement e.g. ZoneId.of("Europe/London")
        ZonedDateTime zdt = Instant.ofEpochMilli(Long.parseLong(timestamp)).atZone(ZoneId.systemDefault());
        System.out.println(zdt);

        zdt = zdt.plusDays(10);
        System.out.println(zdt);

        // Custom format
        System.out.println(DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH).format(zdt));
    }
}

Output:

2021-05-12T16:08:54.319+01:00[Europe/London]
2021-05-22T16:08:54.319+01:00[Europe/London]
05/22/2021

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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