Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a timestamp from string

So I have been trying to take off a timestamp from a string, a file name to be more specific.

I tried making a substring, but the size of the timestamp is variable.

For example, sometimes it's like this:

2016-05-05 03:45:00.907text.txt

and sometimes like this:

2016-05-05 03:45:00.83text.txt

Maybe regex is the answer?

The string to be processed will always have a timestamp plus a filename. The filename can start with numbers or letters.

I forgot to say it's for Java.

like image 575
Zamaking Avatar asked Apr 29 '26 02:04

Zamaking


2 Answers

String input = "2016-05-05 03:45:00.907text.txt";
String regex = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d+";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS");
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);

if(matcher.find()){
    String output  =  matcher.group();

    Date date = formatter.parse(output);
    long time = date.getTime();

    System.out.println(time);
}

You have to find the date with regex, then you convert the String in a proper Date and then you can get the timestamp.

like image 156
Troncador Avatar answered Apr 30 '26 15:04

Troncador


this sed will cleanup the timestamp

$ echo "2016-05-05 03:45:00.83text.txt" | 
 sed -r 's/^[0-9]{4}(-[0-9]{2}){2} ([0-9]{2}:){2}[0-9]{2}\.[0-9]{2,3}//'

text.txt

will also work for the other case, however it will not know the difference if your file name is "7text.txt".

like image 45
karakfa Avatar answered Apr 30 '26 15:04

karakfa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!