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?
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.
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.
JavaScript Date getUTCDate() getUTCDate() returns the day of the month (1 to 31) of a date object. getUTCDate() returns the day according to UTC.
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.
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()
(get-date).ToUniversalTime().ToString("yyyyMMddTHHmmssfffffffZ")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With