Skip to content

Add One New DateTime Parsing Format #11719

@scotthardwick

Description

@scotthardwick

Yesterday I posted a suggestion that we have a new special format for Get-Date that creates the SecondsSinceEpoch (aka UnixTime) for users.

Additionally I think we should have built into the language the ability to easily parse a UnixEpoch timestamp back into a DateTime.

Various existing parsing that works today:

$aDate = [DateTime]"2020-01-28T17:32:18.4986003-06:00" #  (conversion back from the format of Format "o")
$bDate = [DateTime]"2020-01-28T17:36:39" #  (conversion back from the format of Format "s")
$cDate = [DateTime]"Tue, 28 Jan 2020 17:37:43 GMT" #  (conversion back from the format of Format "r")
$dDate = [DateTime]"2020-01-28 17:38:24Z" #  (conversion back from the format of Format "u")
$eDate = [DateTime]"7/25/2013 6:37:31 PM" 
$fDate = [DateTime]"2013-07-25 14:26:00" 
$gDate = [DateTime]"7/25/2013 14:26:00"
$hDate = [DateTime]"2013-07-25 6:37:31 PM"

But we can't currently put in $AUnixDate = [DateTime]"1374755180" and end up with a valid DateTime object (which would be of UTC kind)

A discussion by Randy James at https://stackoverflow.com/questions/17859421/parse-datetime-in-multiple-formats suggests perhaps something along these lines for processing this in another language:

public DateTime ParseRequestDate()
{
    // https://stackoverflow.com/questions/2883576/how-do-you-convert-epoch-time-in-c

    CultureInfo enUS = new CultureInfo("en-US");

    var dt = "1374755180";
    //var dt = "7/25/2013 6:37:31 PM";
    //var dt = "2013-07-25 14:26:00";

    DateTime dateValue;
    long dtLong;

    // Scenario #1
    if (long.TryParse(dt, out dtLong))
        return dtLong.FromUnixTime();

    // Scenario #2 & #3
    var formatStrings = new string[] { "MM/dd/yyyy hh:mm:ss tt", "yyyy-MM-dd hh:mm:ss" };
    if (DateTime.TryParseExact(dt, formatStrings, enUS, DateTimeStyles.None, out dateValue))
        return dateValue;

    throw new SomeException("Don't know how to parse...");
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Enhancementthe issue is more of a feature request than a bugResolution-FixedThe issue is fixed.WG-Cmdlets-Utilitycmdlets in the Microsoft.PowerShell.Utility module

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions