Skip to content

Instantly share code, notes, and snippets.

@selfawaresoup
Last active August 29, 2015 14:20
Show Gist options
  • Save selfawaresoup/c0b7c177220e4af8fc78 to your computer and use it in GitHub Desktop.
Save selfawaresoup/c0b7c177220e4af8fc78 to your computer and use it in GitHub Desktop.
Getting milliseconds from a DateTime object

Getting milliseconds from a DateTime

Task: get the millisecond component as an actual number (not a string) from a native "datetime" object of some popular dynamic languages.

Ruby

This is incomprehensible

DateTime.now.to_time.to_f % 1 * 1000

Why should I convert to a to a string to do basic math?

DateTime.now.strftime("%L").to_i

PHP

As usual, it's all strings in PHP ...

This "works":

(int)(new DateTime("2015-04-29 12:30:40.1234567+02:00"))->format("u");
//                                            ^

However, this doesn't:

(int)(new DateTime("2015-04-29 12:30:40.12345678+02:00"))->format("u");
//                                             ^

Wat?

Also, new DateTime() without any argument will always give you the current date and time with 0 milliseconds. Thanks, PHP ...

JavaScript

Suprisingly, here things actually make sense:

(new Date()).getMilliseconds()

Python

Not perfect, but acceptable

datetime.now().microsecond / 1000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment