Javascript Date object returning April 31? [duplicate] - javascript

This question already has answers here:
javascript is creating date wrong month
(4 answers)
Closed 5 years ago.
There seems to be an error with the Date object in Javascript, it thinks April 31, 2017 is a real day. I discovered this by trying to get the date 90 days ago from today (August 29). The following is a snippet of my code for context:
*Edit: For context, this is in Google Apps Script technically.
var now = new Date();
var ninetyDaysAgo = new Date(now.getTime() - 90 * 1000 * 60 * 60 * 24);
var dateStr = ninetyDaysAgo.getFullYear() + '-' +
ninetyDaysAgo.getMonth() + '-' +
ninetyDaysAgo.getDate();
//If I print dateStr it's '2017-4-31'
This is important because I need the correct date to use an API. Is this just a thing in the date class or am I missing something?

getMonth is zero-based. So you need to use it like below:
var dateStr = ninetyDaysAgo.getFullYear() + '-' +
(ninetyDaysAgo.getMonth() + 1) + '-' +
ninetyDaysAgo.getDate();

Related

How to convert UTC to IST time format [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Convert date to another timezone in JavaScript
(34 answers)
Closed 5 years ago.
Input:- 2018-01-19T17:04:54.923Z;
Output:- 2018-01-19 17:04:54;
How can I get universal logic which will work in all browsers in JAVASCRIPT
You can use this:
var dt = new Date('2018-01-19T17:04:54.923Z');
var formatedString = dt.getFullYear() + "-" + dt.getMonth() + 1 + "-" + dt.getDate() + " " + dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
console.log(formatedString);
In javascript you can convert UTC date to local date format using below snippets.
// Your input date
var utcDate = new Date('2018-01-19T17:04:54.923Z');
//Converted UTC to local(IST, etc.,,)
console.log(utcDate.toUTCString());
/*
Output is : "Fri, 19 Jan 2018 17:04:54 GMT"
*/

How can I count the days between two dates in javascript? (without year) [duplicate]

This question already has answers here:
How to calculate date difference in JavaScript? [duplicate]
(24 answers)
Closed 5 years ago.
How can I count the days between two dates in javascript? (without years only month and day for every years)
for example: Mai 6 (Without 2017) to Nov 7 (Without 2017) DAY:1, DAY:2, DAY:3..... And Nov 8 (Without 2017) to Mai 5 Next year (Without 2018) DAY:1, DAY:2, DAY:3..... I Have thish code but calculating the days only for this year and not from November 8 to next year Mai 5
var day=1000*60*60*24;
var d1 = Date.parse('Jan 1');
var d2 = Date.parse('Jun 30');
var diff = d2 - d1;
Math.round(diff/day)
You were looking for the Date.parse function.
Take a look here at how it will be handled without a year being passed in.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
EDIT:
Here is a function that will append the current year and parse the dates. This is not code that should ever make it into production because the slightest change in the format of the date will break it. But to save face for the wrong solution I proposed try using this:
function getDays(strDay1, strDay2){
var day=1000*60*60*24;
strDay1 = strDay1 + ' ' + (new Date().getFullYear());
strDay2 = strDay2 + ' ' + (new Date().getFullYear());
var d1 = Date.parse(strDay1);
var d2 = Date.parse(strDay2);
var diff = d2 - d1;
return Math.round(diff/day)
}
alert(getDays('Jan 1', 'Jun 30'));

Adjusting JavaScript Date and Time [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Formatting a date in JavaScript
How to get datetime in javascript?
I've found a script that displays the current date and time in various time zones. I can't figure out how to change the format. Currently, it displays as MM/DD/YYYY HH:MM:SS AM/PM and I want it to just display as HH:MM AM/PM
I'm more skilled with jQuery than plain JavaScript, and this is confounding me:
$(document).ready(function() {
function calcTime(offset) {
currentDate = new Date();
utc = currentDate.getTime() + (currentDate.getTimezoneOffset() * 60000);
newDate = new Date(utc + (3600000*offset));
return newDate.toLocaleString();
}
function displayTimes() {
$("#chicago").html(calcTime("-6"));
$("#london").html(calcTime("+1"));
$("#shanghai").html(calcTime("+8"));
};
window.setInterval(displayTimes, 1000);
});
The culprit is the following line.
return newDate.toLocaleString();
Specifically, toLocaleString()
You can find out more about what that line's doing here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
A quick way would be to use .toTimeString()
Instead of returning newDate.toLocaleString() or .toTimeString() you want to make it print as you wish it to.
e.g.
return newDate.getHours() + ':' newDate.getMinutes();
That'll give you the military time.
If you want am/pm display, this can get that for you
(newDate.getHours() > 11) ? 'pm' : 'am'
If you want the time prettified, 0 is 12 midnight, and 12 is noon. You can subtract 12 if the hours are greater than 12. If 0, you can also set it to display 12. All that can be done like this:
(newDate.getHours() === 0) ? 12 : ((newDate.getHours() > 12) ? newDate.getHours() - 12 : newDate.getHours());
Should definitely use a var for newDate.getHours(). Speaking of vars...
Please reformat your vars as such:
var currentDate = new Date(),
utc = currentDate.getTime() + (currentDate.getTimezoneOffset() * 60000),
newDate = new Date(utc + (3600000*offset));
Hope that helps.
EDIT: All together now:
replace the following
return newDate.toLocaleString();
with the following
return (newDate.getHours() === 0) ? 12 : ((newDate.getHours() > 12) ? newDate.getHours() - 12 : newDate.getHours()) + ' : ' + newDate.getMinutes() + ' ' + (newDate.getHours() > 11) ? 'pm' : 'am';
That's rather sloppy, and hurriedly written, but if you use a var for newDate.getHours() it'll be an easier read.
Thanks.
var myDate= new Date();
myDate.format("h:mm tt");
http://www.jslab.dk/library/date.format

Day of tomorrow's show date in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Add days to DateTime using JavaScript
if today's date of 5-12-2012, I want to display the date the next day 6-12-2012. How is that coded in javascript?
var date = "5-12-2012";
var datum = new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.getDate() + "-" + (datum.getMonth() + 1) + "-" + datum.getFullYear();

How to calculate years and months between two dates in Javascript?

Is there a way to calculate the count of years (considering leap years also) and months between two different dates in Javascript?
Here is the best way I know to get years and months:
// Assumes Date From (df) and Date To (dt) are valid etc...
var df= new Date("01/15/2010");
var dt = new Date("02/01/2012");
var allMonths= dt.getMonth() - df.getMonth() + (12 * (dt.getFullYear() - df.getFullYear()));
var allYears= dt.getFullYear() - df.getFullYear();
var partialMonths = dt.getMonth() - df.getMonth();
if (partialMonths < 0) {
allYears--;
partialMonths = partialMonths + 12;
}
var total = allYears + " years and " + partialMonths + " months between the dates.";
var totalMonths = "A total of " + allMonths + " between the dates.";
console.log(total);
console.log(totalMonths);
return {jaren: allYears, maanden: partialMonths};
This might be a helpful source:
http://www.merlyn.demon.co.uk/js-date1.htm#DYMD
The following snippet contains my solution. It's based on the idea that a currentDate - pastDate already is the result.
If you don't want negative results, you have to check that years and month is not less than 0.
const pastDate = '1989-02-10'
const period = new Date(new Date().getTime() - new Date(pastDate).getTime())
const years = period.getFullYear() - 1970 // at 1970 the date calendar starts
const months = period.getMonth()
console.log('years: ', years, ', month: ', months)
You will find a complete javascript function here with validation.
Edit: Link is dead - here is a simple JS line that calculates the difference in months between two dates:
return dateTo.getMonth() - dateFrom.getMonth() +
(12 * (dateTo.getFullYear() - dateFrom.getFullYear()));
That is assuming that you have the dates in two variables called dateTo and dateFrom.
Have a look at the JavaScript Date object.

Categories

Resources