Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a DateTime object with a specific UTC DateTime in PowerShell

I'm trying to create a DateTime object with a specific UTC timestamp in PowerShell. What's the simplest way to do this?

I tried:

Get-Date     -Format (Get-Culture).DateTimeFormat.UniversalSortableDateTimePattern     -Date "1970-01-01 00:00:00Z" 

but I get this output:

1969-12-31 19:00:00Z 

It's a few hours off. Where's my lapse in understanding?

like image 783
sourcenouveau Avatar asked May 07 '12 18:05

sourcenouveau


People also ask

How do I set DateTime to UTC?

The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo. ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method.

How do I create a UTC timestamp?

Use the getTime() method to get a UTC timestamp, e.g. new Date(). getTime() . The method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation.

How can I get only the date from UTC?

JavaScript Date getUTCDate() getUTCDate() returns the day of the month (1 to 31) of a date object. getUTCDate() returns the day according to UTC.

How do I create a date object in PowerShell?

Format DateTime Objects in PowerShell To change the date and time format of a DateTime object, use the Get-Date command to generate the object and the -Format parameter to change the layout. The -Format parameter accepts a string of characters, representing how a date/time string should look.


2 Answers

The DateTime object itself is being created with the proper UTC time. But when PowerShell prints it out it converts it to my local culture and time zone, thus the difference.

Proof:

$UtcTime = Get-Date -Date "1970-01-01 00:00:00Z" $UtcTime.ToUniversalTime() 
like image 76
sourcenouveau Avatar answered Oct 08 '22 23:10

sourcenouveau


(get-date).ToUniversalTime().ToString("yyyyMMddTHHmmssfffffffZ") 
like image 29
Ryker Abel Avatar answered Oct 08 '22 23:10

Ryker Abel