从字符串中删除日期和时间戳

时间:2019-07-18 12:15:48

标签: c# json string datetime

我有一个字符串,其中包含一个由bottomTabNavigator生成的日期和timpestamp,如下所示:

$billings = DB::table('billing as b')
    ->select(
       'b.sender', 
       'b.message',
       'b.amount',
       DB::raw('DATE(b.created_at) as billing_date'),
       'b.billing_type', 
       'b.service_name',
       'b.package_name'
  )                                                         
 ->orderByRaw('b.created_at DESC')
 ->groupBy('sender')  //added
 ->having('sender', '>', 1) //added
 ->get(); 

字符串的结构类似于json数组,例如:

DateTime.Now

我将其作为未格式化的字符串。

如何从其余字符串中删除DateTime标记?

1 个答案:

答案 0 :(得分:4)

您可以尝试正则表达式Regex.Replace

代码:

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 + "\"");

演示:

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

结果:

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