I'm currently using an API that's returning a timestamp in a weird format that I'm struggling to parse into a unix timestamp for my database, the result I'm receiving is:
"date": "20190412T131518.000Z",
I've tried using:
var date = new Date(array.date);
console.log(date.parse);
Which just returns NaN so I'm unsure where to go with it
You could add some dashes and colons.
20190412T131518.000Z // input
2019-04-12T13:15:18.000Z // needed format
It looks like, that Date does not fully accept date string in ISO 8601 format. It respects only a version from the standard in the form
YYYY-MM-DDTHH:mm:ss.sssZ
var string = "20190412T131518.000Z",
date = new Date(string.replace(/(....)(..)(.....)(..)(.*)/, '$1-$2-$3:$4:$5'));
console.log(date);
You can parse from the string to the Date object as below:
let rawDate = "20190412T131518.000Z";
let myDate = new Date(Date.UTC(
rawDate.substr(0, 4),
rawDate.substr(4, 2),
rawDate.substr(6, 2),
rawDate.substr(9, 2),
rawDate.substr(11, 2),
rawDate.substr(13, 2)
));
console.log(myDate);
Related
Suppose I've got a date in string format, such as "2021-07-19". How can I subtract x days from this date that is represented as a string?
I have tried to convert the string into a date first, then subtract the number of days, and convert back to a string, but that doesn't work.
const dateString = "2021-07-19"
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayDateString = previousDayDate.toString()
The ultimate result should be "2021-07-18". Instead, I get the date as a full string: Sun Jul 18 2021 01:00:00 GMT+0100 (British Summer Time)
The reason you get the wrong date is that "2021-07-19" is parsed by built–in parsers as UTC, but all the other methods you're using are local, so you appear to get the wrong date or time. Other than that, your algorithm is sound. Just parse the string as local to being with:
// Parse string in YYYY-MM-DD format as local
function parseISOLocal(s) {
let [Y, M, D] = s.split(/\W/);
return new Date(Y, M-1, D);
}
console.log(parseISOLocal('2021-07-20').toString());
This is a very common issue.
Note, the snippet below didn't work in my locale until I changed the input date to YYYY-MM-DD.
// const dateString = "2021-19-07" - your format
const dateString = "2021-07-19" // format testable in my locale
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayDateString = `${previousDayDate.getFullYear()}-${('0' + (previousDayDate.getMonth()+1)).slice(-2)}-${('0' + previousDayDate.getDate()).slice(-2)}`;
console.log(previousDayDateString)
Using Moment.js
const dateString = moment("2021-07-19", "YYYY-MM-DD").startOf("day")
const previousDayDateString = dateString.subtract(1, "days").format("YYYY-MM-DD");
Thank you all for the suggestions. I followed the same convention as Spencer's comment above (How to format a JavaScript date?) by doing:
const dateString = "2021-07-19"
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayString = previousDayDate.toLocaleDateString("en-CA").split(",")[0]
console.log(previousDayString)
I am trying to convert string to time, the string i have are in this format, '8:3' and '16:45'.
I want to convert UTC time in jQuery.
You can write your function to create UTC date with the time string.
function toUTC(str) {
let [h, m] = str.split(':');
let date = new Date();
date.setHours(h, m, 0)
return date.toUTCString();
}
console.log(toUTC('8:3'))
console.log(toUTC('16:45'))
You don't need jQuery for such operations. Just the simple Date object will do the trick. Say you want to convert time from a specific date.
let date = new Date('2020-04-01'); // leave the Date parameter blank if today
date.setHours(16); // must be 24 hours format
date.setMinutes(45);
let theUTCFormat = date.getUTCDate();
Cheers,
I get the date from server in such format: 2019-01-24 00:00:00
How to convert it to 24-01-2019?
I use:
new Date(dateFromServer).toLocaleDateString()
but it returns 01/24/19.
as seen here Format date to MM/dd/yyyy in JavaScript
var date = new Date(dateFromServer);
alert(date.getDate() + '-' + (date.getMonth() + 1) + '-' + date.getFullYear());
Avoid answers that suggest parsing, it doesn't make sense to parse a string to a Date and reformat it just to get back the values you started with, given the risks of using the built–in parser (e.g. in Safari, new Date('2019-01-24 00:00:00') returns an invalid Date).
To reformat a date, just split it into the parts and put it back as you want:
// #param {string} s - timestamp in format YYYY-MM-DD HH:mm:ss
function reformatDateString(s) {
var b = s.split(/\D/);
return `${b[1]}/${b[2]}/${b[0]}`
}
console.log(reformatDateString('2019-01-24 00:00:00'));
Using the following:
var timestart = $('.thisDiv').data("timestart");
var startDateTime = new Date(timestart);
to collect a date from a php file that is updating by ajax from this:
$TimeStart = date( 'Y,m,d,g,i', $TimeStart );
<div class="thisDiv" data-timestart="<?= $TimeStart ?>"></div>
var timestart = $('.thisDiv').data("timestart");
In console I'm getting the following when logging timestart and startDateTime:
2017,07,24,7,50
Invalid Date
If I paste the date that is output as follows
var startDateTime = new Date(2017,07,24,7,50);
Then it works fine. Any ideas why I'm getting Invalid Date?
Your timestart variable (JavaScript) is just a string. So it's a string 2017,07,24,7,50, and not those elements in order - which can't be used as separate parameters like new Date() expects.
Let's take a look at it!
var startDateTime = new Date(2017,07,24,7,50); // Parameters in order - all OK!
var startDateTime = new Date("2017,07,24,7,50"); // A single string - single parameter, not OK!
You need to return a proper format of dates from PHP with a format that's valid in JavaScript. Per the ECMAScript standard, the valid format that should work across all browsers is YYYY-MM-DDTHH:mm:ss.sssZ (see the reference at the bottom). To define that from PHP, you would need to format it as such
$TimeStart = date('c', $TimeStart);
This would return a format such as 2017-07-24T21:08:32+02:00.
Alternatively, you can use a splat/spread-operator ... and split the string it into elements, which I find as the better approach than above.
var timestart = $('.thisDiv').data("timestart"); // Get the string: "2017,07,24,7,50"
timestart = timestart.split(","); // Split into array
var startDateTime = new Date(...timestart); // Pass as arguments with splat-operator
Spread/splat operator in JavaScript
PHP date() documentation
ECMAScript date string (JavaScript)
You need to convert your date from string format to numbers.
var timestart = $('.thisDiv').data("timestart").split(",").map(Number);
var startDateTime = new Date(...timestart);
console.log(startDateTime)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="thisDiv" data-timestart="2017,07,24,7,50"></div>
I need help to convert input string that looks something like 20160313023000 (invalid daylight saving date) to date in yyyyMMddHHmmss format using JavasScript.
I tried new Date('20160313023000').getTime() but the output that I get is 1969/12/31 19:00:00.000
That will parse your date:
function parseDate(date) {
// format: yyyyMMddHHmmss
var parsedDate = new Date(date.substr(0, 4),
date.substr(4, 2),
date.substr(6, 2),
date.substr(8, 2),
date.substr(10, 2),
date.substr(12, 2));
console.log(parsedDate);
}
parseDate("20160313023000");
But the "invalid daylight saving" actually depends on your locale.