Javascript UTC Date different values - javascript

I have a date in the format dd.mm.yyyy
I use a function to convert this date to MM-DD-YYYY
stringToStringDateFormat(objectData: any): string {
return moment(objectData, 'DD.MM.YYYY').format('MM-DD-YYYY');
}
I want to set hours minutes and seconds to 0
ad send the date in ISO format so i used the following code :
new Date(new Date(this.stringToStringDateFormat("19.07.2021")).setUTCHours(0,0,0,0)).toISOString();
yet the issue I have is I get a different day
for example in this case I get 2021-07-18T00:00:00.000Z
while in reality, it should be 2021-07-19T00:00:00.000Z
how can I get my code to get me the same date I provided and not the date -1 ?

Here using Date.UTC() and adjusting the month to account for zero index.
const [d, m, y] = `19.07.2021`.split('.').map(Number);
console.log(new Date(Date.UTC(y, (m - 1), d)).toISOString()); // months are 0 indexed

Created a new function that sets the hours, minutes, seconds and milliseconds to 0 and returns the date string in the correct format. See this answer for a more detailed look on the methods I used.
function stringToStringDateFormatStartDay(objectData) {
const newD = moment(objectData, "DD.MM.YYYY").utcOffset(0).set({
hour: 0,
minute: 0,
second: 0,
millisecond: 0
});
newD.toISOString();
newD.format("MM-DD-YYYY");
return newD;
}
const d = stringToStringDateFormatStartDay("19.07.2021");
console.log(d)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Parsing with a library to create an interim unsupported format then parsing with the built–in parser is not a good idea.
If you just want to reformat dd.mm.yyyy as yyyy-mm-ddT00:00:00Z then just reformat the string, there is no need to convert to Date object or use a library:
function reformatTimestamp(s) {
return `${s.split(/\D/).reverse().join('-')}T00:00:00Z`;
}
console.log(reformatTimestamp('19.07.2021'));

Related

convert string to UTC time using jquery

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,

How can I convert a date into an integer?

I have an array of dates and have been using the map function to iterate through it, but I can't figure out the JavaScript code for converting them into integers.
This is the array of dates:
var dates_as_int = [
"2016-07-19T20:23:01.804Z",
"2016-07-20T15:43:54.776Z",
"2016-07-22T14:53:38.634Z",
"2016-07-25T14:39:34.527Z"
];
var dates = dates_as_int.map(function(dateStr) {
return new Date(dateStr).getTime();
});
=>
[1468959781804, 1469029434776, 1469199218634, 1469457574527]
Update:
ES6 version:
const dates = dates_as_int.map(date => new Date(date).getTime())
The getTime() method on the Date returns an “ECMAScript epoch”, which is the same as the UNIX epoch but in milliseconds. This is important to note as some other languages use UNIX timestamps which are in in seconds.
The UNIX timestamp and is equivalent to the number of milliseconds since January 1st 1970. This is a date you might have seen before in databases or some apps, and it’s usually the sign of a bug.
Using the builtin Date.parse function which accepts input in ISO8601 format and directly returns the desired integer return value:
var dates_as_int = dates.map(Date.parse);
Here what you can try:
var d = Date.parse("2016-07-19T20:23:01.804Z");
alert(d); //this is in milliseconds
You can run it through Number()
var myInt = Number(new Date(dates_as_int[0]));
If the parameter is a Date object, the Number() function returns the number of milliseconds since midnight January 1, 1970 UTC.
Use of Number()
if your format date is YYYY/M/D you can use this code :
let yourDate = momentjs(new Date().toLocaleDateString(), 'M/D/YYYY').format('YYYY-MM-DD');
let newDate = Number(yourDate.slice(0, 10).split('-').join(''));

Javascript: Returning how many seconds to an date in a format 0000-00-00 00:00:00

I'm using FlipClock to do a countdown to a certain date. The date I'm counting down to is in this format: 0000-00-00 00:00:00.
I want to get how many seconds it is until the date. So I can use in my flipclock.
var clock = $('#countdown').FlipClock(seconds, {
clockFace: 'HourlyCounter',
countdown: true,
callbacks: {
stop: function() {
//callback
}
}
});
I guess your date is in an ISO 8601 like format of yyyy-mm-dd hh:mm:ss and should be interpreted as a local time. In that case, parse the string, convert it to a Date object and subtract it from now to get the difference in milliseconds. Divide by 1,000 to get the difference in seconds, e.g.
// Parse string in yyyy-mm-dd hh:mm:ss format
// Assume is a valid date and time in the system timezone
function parseString(s) {
var b = s.split(/\D+/);
return new Date(b[0], --b[1], b[2], b[3], b[4], b[5]);
}
// Get the difference between now and a provided date string
// in a format accepted by parseString
// If d is an invalid string, return NaN
// If the provided date is in the future, the returned value is +ve
function getTimeUntil(s) {
var d = parseString(s);
return d? (d - Date.now())/1000|0 : NaN;
}

Given a ISO 8601 date/time, how to use JS date() to get the day of the week (0-6)?

Given a datetime string like so:
mystring = '2012-10-23T02:40:59Z'
I need to be able to get the day of the week (0-6) from the string.
How can I pass the above to JS so I can do something like so:
var d = new Date(mystring);
var n = d.getDay();
console.log(n)
where n returns 0-6.
Thank you
While the Date object should be able to parse the ISO 8601 format in ECMA-262, it does not work reliably across browsers so you are much better off to parse them manually:
function isoStringToDate(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], --b[1], b[2], b[3]||0, b[4]||0, b[5]||0, b[6]||0));
}
You can then use the getDay method to get the day number (Sunday = 0, Saturday = 6):
isoStringToDate('2012-10-23T02:40:59Z').getDay(); // 2 for me
Do what you proposed!
Date - getDay()
Returns the day of the week for the specified date according to local time.

How to convert date in format "YYYY-MM-DD hh:mm:ss" to UNIX timestamp

How can I convert a time in the format "YYYY-MM-DD hh:mm:ss" (e.g. "2011-07-15 13:18:52") to a UNIX timestamp?
I tried this piece of Javascript code:
date = new Date("2011-07-15").getTime() / 1000
alert(date)
And it works, but it results in NaN when I add time('2011-07-15 13:18:52') to the input.
Use the long date constructor and specify all date/time components:
var match = '2011-07-15 13:18:52'.match(/^(\d+)-(\d+)-(\d+) (\d+)\:(\d+)\:(\d+)$/)
var date = new Date(match[1], match[2] - 1, match[3], match[4], match[5], match[6])
// ------------------------------------^^^
// month must be between 0 and 11, not 1 and 12
console.log(date);
console.log(date.getTime() / 1000);
Following code will work for format YYYY-MM-DD hh:mm:ss:
function parse(dateAsString) {
return new Date(dateAsString.replace(/-/g, '/'))
}
This code converts YYYY-MM-DD hh:mm:ss to YYYY/MM/DD hh:mm:ss that is easily parsed by Date constructor.
You've accepted an answer, but a much simpler regular expression can be used:
function stringToDate(s) {
s = s.split(/[-: ]/);
return new Date(s[0], s[1]-1, s[2], s[3], s[4], s[5]);
}
alert(stringToDate('2011-7-15 20:46:3'));
Of course the input string must be the correct format.
Months start from 0, unlike the days! So this will work perfectly (tested)
function dateToUnix(year, month, day, hour, minute, second) {
return ((new Date(Date.UTC(year, month - 1, day, hour, minute, second))).getTime() / 1000.0);
}
This returns number of milliseconds since Jan. 1st 1970:
Date.parse('2011-07-15 10:05:20')
Just divide by 1000 to get seconds instead of milliseconds..

Categories

Resources