0

I have a set of text files, some of 10k lines long, some lines contain dates of format;

'Fri Feb 3 16:49:18 2012'

How can i replace this date with a epoch? Im struggling to recognize it among the rest of the test via regex or any other way.

eg of some lines....

Name:branding-SLES Relocations: (not relocatable) Version:11 Vendor: SUSE LINUX Products GmbH, Nuernberg, Germany Release:3.20.30 Build Date: Fri Feb 3 16:49:18 2012 Install Date: Wed Sep 24 16:22:53 2014 Build Host: gubaidulina Group:System/Fhs Source RPM: branding-SLES-11-3.20.30.src.rpm

Fearghal
  • 10,569
  • 17
  • 55
  • 97
  • What exactly do you mean by "replace this date with a epoch"? An "epoch" is a specific reference date. For example, the "Unix Epoch" is Jan 1st 1970 UTC. See [this Wikipedia article](http://en.wikipedia.org/wiki/Epoch_(reference_date)). Did you mean something else? – Matt Johnson-Pint Oct 09 '14 at 17:02
  • Sorry i meant replace with seconds since 1970. – Fearghal Oct 09 '14 at 17:04

4 Answers4

1

May not be perfect, but something to start

(Sun|Mon|Tue|Wed|Thu|Fri|Sat)[\s](Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[\s][1-31][\s][0-9]{2}:[0-9]{2}:[0-9]{2}[\s][0-9]{4}

Referred Regular Expression Matching a Valid Date

Arvind Singh
  • 733
  • 1
  • 10
  • 31
1

It's not necessary to do it with regex yourself. You may write a method like this:

public static long ParseAsUnixTimestampSeconds(String s) {
    DateTime unixEpoch=new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    var pattern="ddd MMM d HH:mm:ss yyyy";

    var dt=DateTime.ParseExact(
        s, pattern, CultureInfo.InvariantCulture, DateTimeStyles.None);

    return (long)(dt-unixEpoch).TotalSeconds;
}

and just call it:

Debug.Print("{0}", ParseAsUnixTimestampSeconds("Fri Feb 3 16:49:18 2012"));

For a better design, have a look at Mr. Skeet's answer:

Unix time conversions in C#

Community
  • 1
  • 1
Ken Kin
  • 4,503
  • 3
  • 38
  • 76
0

I figured this would do the time part, but Arvind had a more complete solution. thxs.

output = Regex.Replace(output, @"[0-2][0-9]:[0-5][0-9]:[0-5][0-9]", "", RegexOptions.None | RegexOptions.Multiline); 
Fearghal
  • 10,569
  • 17
  • 55
  • 97
  • hmm, your search string gets more valid time 00-59. I overlooked and assumed time could include single digit for hour/min/sec so used [0-9]{2}, but if that is not the case and it shouldn't be then your time string is good. Post your final version. – Arvind Singh Oct 09 '14 at 18:42
0

This can be done with DateTime.ParseExact

String DateAsText = "Fri Feb 3 16:49:18 2012";
String Format = "ddd MMM d HH:mm:ss yyyy";
DateTime DateAsDateTime = DateTime.ParseExact(DateAsText, Format, null);
TimeSpan timeSpan = (DateAsDateTime - new DateTime(1970, 1, 1, 0, 0, 0));
Kevin Adams
  • 123
  • 7