How to use ParseExact format when adb shell date returned value with multiple formats

91 views Asked by At

adb shell date returned the string : Wed May 18 19:18:08 IST 2022

I am able to parse this string using

DateTime currentdateTime = DateTime.ParseExact(deviceCurrentDateTime, "ddd MMM dd HH:mm:ss 'IST' yyyy", CultureInfo.InvariantCulture);

But when adb shell date returned the string : Thu May 5 19:18:01 IST 2022 (two spaces after May)

then above parseExact is not working.

How to use multiple formats to parse the two dates?

1

There are 1 answers

2
DubDub On

You can do something like this where you replace your double space with a single space. Usually you'd expect to see a 0 rather than a space in most cases, but hey ho.

var deviceCurrentDateTime = "Thu May  5 19:18:01 IST 2022";
deviceCurrentDateTime = deviceCurrentDateTime.Replace("  ", " ");
DateTime currentdateTime = DateTime.ParseExact(deviceCurrentDateTime, "ddd MMM d HH:mm:ss 'IST' yyyy", CultureInfo.InvariantCulture);

Note I've also replaced your format string with "ddd MMM d HH:mm:ss 'IST' yyyy"

EDIT:

Example where it's working

static void Main(string[] args)
{
    var deviceCurrentDateTime = "Thu May  5 19:18:01 IST 2022";
    deviceCurrentDateTime = deviceCurrentDateTime.Replace("  ", " ");
    DateTime currentdateTime = DateTime.ParseExact(deviceCurrentDateTime, "ddd MMM d HH:mm:ss 'IST' yyyy", CultureInfo.InvariantCulture);
    Console.WriteLine(currentdateTime.ToString());
}

Prints: 05/05/2022 19:18:01

static void Main(string[] args)
{
    var deviceCurrentDateTime = "Wed May 18 19:18:01 IST 2022";
    deviceCurrentDateTime = deviceCurrentDateTime.Replace("  ", " ");
    DateTime currentdateTime = DateTime.ParseExact(deviceCurrentDateTime, "ddd MMM d HH:mm:ss 'IST' yyyy", CultureInfo.InvariantCulture);
    Console.WriteLine(currentdateTime.ToString());
}

Prints: 18/05/2022 19:18:01