3

I want convert milliseconds to date time follow the format mm/dd/yyyy in powershell, my code is below:

$data+= $dataList.Rows[$i]["ROOM_LASTVISITDATE"].ToString() + "`t"

The result of 1278504562790. So, how i can convert it to date time in powershell, please help me. Thanks

John.D
  • 55
  • 1
  • 7
  • 1
    What would be the expected date for the sample input? Also, see [relevant question](https://stackoverflow.com/q/10781697/503046) that deals with seconds. – vonPryz Aug 07 '18 at 12:19
  • 1
    This sounds like two independent questions: "How to parse a DateTime from Unix Epoch format?", and "How to format a DateTime using a custom format string". Both have answers already: https://stackoverflow.com/questions/10781697/convert-unix-time-with-powershell and https://stackoverflow.com/questions/2249619/how-to-format-a-datetime-in-powershell – Joshua Shearer Aug 07 '18 at 12:44

2 Answers2

4

To convert a epoch/unix timestamp to a human readable date with Powershell, you can use the DateTimeOffset type.

[datetimeoffset]::FromUnixTimeMilliseconds(1278504562790).DateTime

Your code could then look like this

$lastVisited = $dataList.Rows[$i]["ROOM_LASTVISITDATE"].ToString()
$data += [datetimeoffset]::FromUnixTimeMilliseconds($lastVisited) + "`t"

stalskal
  • 1,181
  • 1
  • 8
  • 16
3

Assuming the offset is the start of the UNIX epoch (01/01/1970), you could simply add the milliseconds to that offset:

$EpochStart = Get-Date 1970-01-01T00:00:00
$myDateTime = $EpochStart.AddMilliseconds(1278504562790)
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • This will add the current time's hours/minutes/seconds/milliseconds to the provided timestamp, as you're not setting them to 0. To handle this properly, change the parameters in the first line to `Get-Date -Day 1 -Month 1 -Year 1970 -Hour 0 -Minute 0 -Second 0 -Millisecond 0` – Nameless Voice May 07 '20 at 14:51