Nightscape
Nightscape

Reputation: 464

Remove Date and Timestamp from string

I have a string which contains a date and timpestamp which is generated from a DateTime.Now looking like this:

"2019-07-18T11:29:13.623245Z"

The structure of the string is similair to json array, looking for example like this:

  {
    "caption": "Execution time",
    "name": "ExecutionTime",
    "visible": true,
    "enabled": true,
    "path": "executionTime",
    "description": "Execution time",
    "dataType": "DateTime",
    "writable": true,
    "required": true,
    "number: "0000-00000-00000",
    "controlName": "DateTimePicker",
    "defaultValue": "2019-07-18T11:29:13.623245Z",
    "aspects": []
  },

I have it as a string not formated.

How can I remove the DateTime stamp from the rest of the string?

Upvotes: 0

Views: 292

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

You can try regular expressions, Regex.Replace

Code:

using System.Text.RegularExpressions;

...

Regex regex = new Regex(
  @"\""(?<date>[0-9]{4}-[0-9]{2}-[0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,})?Z?\""");

Func<string, string> convert = (source) =>
  regex.Replace(source, m => "\"" + m.Groups["date"].Value + "\"");

Demo:

  string[] tests = new string[] {
    @"xyz:""2019-07-18T11:29:13.623245Z"",123abc",
    @"""abc""2019-07-18T11:29:13.623245Z""xyz""",
    @"xyz : ""2019-07-18T11:29:13.623245Z"" ,123abc",
  };

  string report = string.Join(Environment.NewLine, tests
    .Select(test => $"{test,-50} => {convert(test)}"));

 Console.Write(report);

Outcome:

xyz:"2019-07-18T11:29:13.623245Z",123abc           => xyz:"2019-07-18",123abc
"abc"2019-07-18T11:29:13.623245Z"xyz"              => "abc"2019-07-18"xyz"
xyz : "2019-07-18T11:29:13.623245Z" ,123abc        => xyz : "2019-07-18" ,123abc

Upvotes: 4

Related Questions