Javascript Converting a date to millisecond - javascript

I am building a counter down .
I have the following code:-
var date = new Date(res.data.created_at);
console.log(date); //Sat Jun 20 2020 23:52:05 GMT+0300 (Arabian Standard Time)
date.setDate(date.getDate() + 3);
console.log(date); //Tue Jun 23 2020 23:52:05 GMT+0300 (Arabian Standard Time)
console.log(date.getMilliseconds()); //0
console.log(date.getTime()); //1592945525000
The counter library i am using is accepting a millisecond as initial count down value.
In the above code i want to get a date from api then add 3 days to it, after that get the milliseconds value from now date time to the 3 days added value.

You can use Date.now() to get the current timestamp, and just do a subtraction:
var endDate = new Date(res.data.created_at);
endDate.setDate(endDate.getDate() + 3);
var diffInMilliseconds = endDate.getTime() - Date.now();

Related

Google Apps Script add month to a date until specific date is reached

I have the following code using Google Apps Script, but when I log it out I get the following results. I want GAS to log the next month and stop once it gets to "lastDateofYear ". For whatever reason, the year doesn't change in my results, it just keeps repeating the current year. Please help.
var thisDate = "Mon Dec 20 00:00:00 GMT-06:00 2021";
var nextYear = Number(currentYear)+1;
var lastDateofYear = new Date("12-31-"+nextYear);
for(var i=thisDate; i <= lastDateofYear; ){
var currentiDate = new Date(i);
var month = currentiDate.getMonth()+1;
i.setMonth((month) % 12);
i.setDate(currentiDate.getDate());
Logger.log(currentiDate);
}
RESULTS:
Mon Dec 20 00:00:00 GMT-06:00 2021
Wed Jan 20 00:00:00 GMT-06:00 2021
Sat Feb 20 00:00:00 GMT-06:00 2021
Sat Mar 20 00:00:00 GMT-05:00 2021
Tue Apr 20 00:00:00 GMT-05:00 2021
Thu May 20 00:00:00 GMT-05:00 2021
Sun Jun 20 00:00:00 GMT-05:00 2021
Tue Jul 20 00:00:00 GMT-05:00 2021
Fri Aug 20 00:00:00 GMT-05:00 2021
Mon Sep 20 00:00:00 GMT-05:00 2021
Wed Oct 20 00:00:00 GMT-05:00 2021
Sat Nov 20 00:00:00 GMT-06:00 2021
Mon Dec 20 00:00:00 GMT-06:00 2021
Wed Jan 20 00:00:00 GMT-06:00 2021
Sat Feb 20 00:00:00 GMT-06:00 2021
Sat Mar 20 00:00:00 GMT-05:00 2021
Tue Apr 20 00:00:00 GMT-05:00 2021
As I understand it, you want to print each month from the given date to the last month of the next year of the given date in the log.
You can do this in the following code:
let start = new Date("Mon Dec 20 00:00:00 GMT-06:00 2021");
let currentYear = new Date().getFullYear();
let nextYear = currentYear + 1;
let end = new Date(nextYear, 11, 31);
while (start <= end) {
// You can use Logger.log() here if you want. I use console.log() for demo purpose
console.log(new Date(start).toDateString());
start.setMonth(start.getMonth() + 1);
}
If I got any part wrong, feel free to point it out to me in the comments.
There is a lot to say about your code:
var thisDate = "Mon Dec 20 00:00:00 GMT-06:00 2021";
That timestamp format is not supported by ECMA-262, so don't use the built–in parser to parse it, see Why does Date.parse give incorrect results?
var nextYear = Number(currentYear)+1;
Where does currentYear come from?
var lastDateofYear = new Date("12-31-"+nextYear);
Parsing of an unsupported format, see above. In Safari it returns an invalid date.
for(var i=thisDate; i <= lastDateofYear; ){
Sets i to the string value assigned to thisDate. Since lastDateOfYear is an invalid date in Safari and Firefox, so the test i <= NaN is never true and the loop is never entered.
var currentiDate = new Date(i);
Parses i, see above.
var month = currentiDate.getMonth()+1;
i.setMonth((month) % 12);
i is a string, which doesn't have a setMonth method so I'd expect a Type error like "i.setMonth is not a function" if the loop actually runs.
i.setDate(currentiDate.getDate());
Another Type error as above (but it won't get this far).
Logger.log(currentiDate);
}
It seems you want to sequentially add 1 month to a date until it reaches the same date in the following year. Trivially, you can just add 1 month until you get to the same date next year, something like:
let today = new Date();
let nextYear = new Date(today.getFullYear() + 1, today.getMonth(), today.getDate());
let result = [];
do {
result.push(today.toString());
today.setMonth(today.getMonth() + 1);
} while (today <= nextYear)
However, adding months is not that simple. If you add 1 month to 1 Jan, you'll get 2 or 3 Mar depending on whether it's a leap year or not. And adding 1 month to 31 Aug will return 1 Oct.
Many "add month" functions check to see if the date rolls over an extra month and if it does, set the date back to the end of the previous month by setting the date to 0, so 31 Jan + 1 month gives 28 or 29 Feb.
But if you cycle over a year using that algorithm, you'll get say 31 Jan, 28 Feb, 28 Mar, 28 Apr etc. rather than 31 Jan, 28 Feb, 31 Mar, 30 Apr, etc.
See JavaScript function to add X months to a date and How to add months to a date in JavaScript?
A more robust way is to have a function that adds n months to a date and increment the months to add rather than the date itself so the month–end problem can be dealt with separately for each addition, e.g.
/* Add n months to a date. If date rolls over an extra month,
* set to last day of previous month, e.g.
* 31 Jan + 1 month => 2 Mar, roll back => 28 Feb
*
* #param {number} n - months to add
* #param {Date} date - date to add months to, default today
* #returns {Date} new Date object, doesn't modify passed Date
*/
function addMonths(n, date = new Date()) {
let d = new Date(+date);
let day = d.getDate();
d.setMonth(d.getMonth() + n);
if (d.getDate() != day) d.setDate(0);
return d;
}
/* return array of n dates at 1 month intervals. List is
* inclusive so n + 1 Dates returned.
*
* #param {Date} start - start date
* #param {number} n - number of months to return
* #returns {Array} array of Dates
*/
function getMonthArray(n, start = new Date()) {
let result = [];
for (let i=0; i<n; i++) {
result.push(addMonths(i, start));
}
return result;
}
// Examples
// Start on 1 Dec
getMonthArray(12, new Date(2021,11,1)).forEach(
d => console.log(d.toDateString())
);
// Start on 31 Dec
getMonthArray(12, new Date(2021,11,31)).forEach(
d => console.log(d.toDateString())
);
The functions don't attempt to parse timestamps to Dates, that responsibility is left to the caller.

How to get total minutes of difference between two dates using pure JavaScript

Updated My Question
How to get total minutes of difference between two dates using pure JavaScript when
Condition (1):: Same month, same year but date changes
newDate: 18/10/2016 0:50
oldDate: 17/10/2016 23:05
Condition (2):: Last date of current month and 1st date of next month
newDate: 1/11/2016 0:50
oldDate: 31/10/2016 23:05
Condition (3):: Last date of year and 1st date of new year
newDate: 1/1/2017 0:50
oldDate: 31/12/2016 23:05
Note: Please have a look newDate and oldDate to understand the conditions.
Thanks
Since you don't want to use a library for parsing date strings, you can write a simple function such as:
// Parse date string in "Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)" format
function parseDate(s) {
// Split into tokens
var b = s.match(/\w+/g) || [];
var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
// Determine offset in minutes
var offSign = /GMT+/.test(s)? -1 : 1;
var offset = b[8].substr(0,2)*60 + +b[8].substr(2,2);
// Create date, applying offset to minutes
var date = new Date(Date.UTC(b[3],
months.indexOf(b[1].toLowerCase()),
b[2],
b[4],
+b[5] + (offSign*offset),
b[6]));
return date;
}
var d = parseDate("Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)")
console.log('UTC: ' + d.toISOString() + '\n' +
'Local: ' + d.toLocaleString());
Completed My Requirements with the below pure JavaScript code
In my code starttime and endtime are
//var startTime = localStorage.getItem("starttime");
//var endTime = new Date();
Example Here.
var startTime = new Date("Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)");
var endTime = new Date("Sun Jan 1 2017 15:35:57 GMT+0530 (India Standard Time)");
var totalMiliseconds = endTime - startTime;
alert(totalMiliseconds);
//output:: 86400000
var totalSeconds = totalMiliseconds/1000;
alert(totalSeconds);
//output:: 86400
var totalMinuts = totalSeconds/60;
alert(totalMinuts);
//output:: 1440
var totalHours = totalMinuts/60;
alert(totalHours);
//output:: 24
And this fulfill my all 3 conditions.
Thank You For Your Support !!!

javascript getTime() returns greater value for older date compared to new date

javascript getTime() returns the number of milliseconds form midnight Jan 1, 1970 and the time value in the Date Object. but,
new Date('Wed Sep 16 2105 05:30:00 GMT+0530').getTime()
// returns 4282502400000
new Date('Tue Oct 26 2015 05:30:00 GMT+0530').getTime()
// returns 1445817600000
Shouldn't the value retuned by the later (Tue Oct 26 2015 05:30:00 GMT+0530) be greater.
I want to find the list dates between a given date (inform of timestamp) and today. I wrote the code below with the assumption that the value returned by getTime() for older dates will always be lesser than newer dates.
var timestamp = new Date('9/15/2105, 12:00:00 AM').getTime();
var startDate = new Date(timestamp);
// Date.UTC() to avoid timezone and daylight saving
var date = new Date(Date.UTC(startDate.getFullYear(),
startDate.getMonth(),
startDate.getDate()
));
var currentDay = new Date();
var currentDayTimestamp = new Date(Date.UTC(currentDay.getFullYear(),
currentDay.getMonth(),
currentDay.getDate()
)).getTime();
// day in millisec, 24*60*60*1000 = 86400000
date = new Date(date.getTime() + 86400000);
var dates = [];
console.info(date + ' : ' + date.getTime());
console.info(new Date(currentDayTimestamp) + ' : ' + currentDayTimestamp);
while(date.getTime() <= currentDayTimestamp) {
var dateObj = {
date: date.getUTCDate(),
month: date.getUTCMonth() + 1,
year: date.getUTCFullYear()
}
dates.push(dateObj);
date = new Date(date.getTime() + 86400000);
}
console.info(JSON.stringify(dates));
OUTPUT:
Wed Sep 16 2105 05:30:00 GMT+0530 (IST) : 4282502400000
Tue Oct 27 2015 05:30:00 GMT+0530 (IST) : 1445904000000
[]
The problem is a typo in your dates. One has the year 2105 which is much larger than 2015.

Javascript Date add days

var date = new Date();
var date2 = new Date();
daysinadvance = document.getElementById('AdvanceDays').value;
date2.setDate(date.getDate()+daysinadvance);
console.log(date2 + date + daysinadvance);
Fri Jan 28 2022 18:13:43 GMT+0000 (GMT Daylight Time)
Mon Apr 28 2014 18:13:43 GMT+0100 (GMT Standard Time)
60
If I pass in a directly typed number so + 60, it works fine but using the variable, I get a date in 2022. All I would like is the date2 to be current date + 60 days so I can update my validation.
Any help please?
Convert the value to a number first, e.g. with the unary plus operator:
var daysinadvance = +document.getElementById('AdvanceDays').value;
// ^ unary plus
Otherwise daysinadvance will be a string and you are doing string concatenation.

Getting current time from the date object

function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0].substring(2), // get only two digits
month = datePart[1], day = datePart[2];
document.write(new Date(day+'/'+month+'/'+year));
}
formatDate ('2010/01/18');
When i print this i get Thu Jun 01 1911 00:00:00 GMT+0530 (India Standard Time) but the system is actually 3:42 P.M
Use the current date to retrieve the time and include that in the new date. For example:
var now = new Date,
timenow = [now.getHours(),now.getMinutes(),now.getSeconds()].join(':'),
dat = new Date('2011/11/30 '+timenow);
you must give the time:
//Fri Nov 11 2011 00:00:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11"));
//Fri Nov 11 2011 23:23:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11 23:23"));
What do you want? Just the time? Or do you want to define a format? Cu's the code expects this format for date: dd/mm/yyyy, changed this to yyyy/mm/dd
Try this:
function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0],
month = datePart[1], day = datePart[2],
now = new Date;
document.write(new Date(year+'/'+month+'/'+day+" " + now.getHours() +':'+now.getMinutes() +':'+now.getSeconds()));
}
formatDate ('2010/01/18')
Output:
Mon Jan 18 2010 11:26:21 GMT+0100
Passing a string to the Date constructor is unnecessarily complicated. Just pass the values in as follows:
new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10))
You're creating a Date() object with no time specified, so it's coming out as midnight. if you want to add the current date and time, create a new Date with no arguments and borrow the time from it:
var now = new Date();
var myDate = new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10),
now.getHours(), now.getMinutes(), now.getSeconds())
No need to strip the last two characters off the year. "2010" is a perfectly good year.

Categories

Resources