Looks like you are really just trying to reformat the input date string (without converting to local time). Your attempt relies on Date
for string parsing, which is not recommended (see JavaScript Date note regarding date string parameters). It also uses toString
which is implementation dependent and can't be relied on to reformat the output to a specific format like yyyy-mm-dd
.
You can't just convert the date string to a Date
object and then rely on methods like getDate()
because those methods return values in local time which may be different than the date values you are trying to preserve from the input date string with a specific timezone.
As noted in other answers, there are lots of libraries you can use for this sort of thing. Otherwise, here are a couple of hacks you can try (beware, variations in your date string input format could break either of these approaches - hence the existence of the libraries).
Credit to @SergeyMetlov for the two digit month and date formatting.
If your date strings are consistently formatted in the same way as your example, just parse the string and reformat the output as desired.
const str = 'Sat Aug 12 2000 00:00:00 GMT+0200 (Midden-Europese zomertijd)';
const format = (d) => (d < 10 ? '0' : '') + d;
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
// parse date string (lazy since time parts not used)
const [day, m, d, yyyy, ...time] = str.split(' ');
// two digit format for month and date
const mm = format(months.indexOf(m) + 1);
const dd = format(d);
// format date as yyyy-mm-dd
const date = `${yyyy}-${mm}-${dd}`;
console.log(date);
// 2000-08-12
Or if you want to force the js date object to submit, then you can try something ugly like the below. The example relies on Date.parse
to parse the input date string which is not recommended since implementations may not be consistent across browsers. If you really wanted to do something like this you should replace Date.parse
(and the clunky substr
line) with some better parsing of your own.
const str = 'Sat Aug 12 2000 00:00:00 GMT+0200 (Midden-Europese zomertijd)';
const format = (d) => (d < 10 ? '0' : '') + d;
const utc = Date.parse(str);
const localoffset = new Date().getTimezoneOffset() * 60000;
const operator = str.substr(28, 1);
const stroffset = (() => {
let offset = str.substr(29, 4) * 60000;
if (operator === '-') {
offset *= -1;
}
return offset;
})();
// convert utc to "wrong" date, will look "right" when formatted
const wrong = new Date(utc + localoffset + stroffset);
const y = wrong.getFullYear();
const m = format(wrong.getMonth() + 1);
const d = format(wrong.getDate());
const output = `${y}-${m}-${d}`;
console.log(output);
// 2000-08-12