Javascript Date from Python datetime string representation
In a recent project I needed to convert the string representation of a Python datetime.datetime into a Javascript Date object. Here’s what I came up with. JavaScript isn’t my best language so if you have any suggestions for improvement, please let me know.
function datetimeToDate(datetime_str, use_utc) {
// Return a JS Date object from the given python datetime_str string.
// if the optional boolean use_utc argument is given, the datetime_str
// will be treated as a UTC datetime_str
"use strict";
var datetime_parts = datetime_str.split(" ", 2),
date_parts = datetime_parts[0].split("-"),
time_parts = datetime_parts[1].split(":"),
second_parts = time_parts[2].split('.'),
mkdate,
s2i,
smu2ims;
use_utc = use_utc === undefined ? false : use_utc;
// The Date constructors don't work with .apply(), so lambdas
if (use_utc) {
mkdate = function (y, m, d, hr, min, sec, ms) {
return new Date(Date.UTC(y, m, d, hr, min, sec, ms));
};
} else {
mkdate = function (y, m, d, hr, min, sec, ms) {
return new Date(y, m, d, hr, min, sec, ms);
};
}
// string to int with radix 10
s2i = function (i_str) { return parseInt(i_str, 10); };
// string microsecond (aka mu) to int millisecond (aka ms)
smu2ims = function (f_str) {
return Math.round(parseFloat(f_str) * 1000);
};
return mkdate(s2i(date_parts[0]), // year
s2i(date_parts[1]) - 1, // month
s2i(date_parts[2]), // day
s2i(time_parts[0]), // hour
s2i(time_parts[1]), // minute
s2i(second_parts[0]), // second
smu2ims("." + second_parts[1])); // millisecond
}