How to create a Date object from year, month and date strings? - javascript

I'm currently just practising JavaScript and I'm trying to create a programme that calculates how many days there are until your next birthday.
I have seen on this site that there is a daysBetween function that I can use to tell the time difference between two dates (I just need to turn these dates into the millisecond value since the 1st Jan 1970).
The problem is that, although one of those dates is the current date (which is easy to convert into its millisecond value), the second is derived from answers the user inputs as a string into a prompt command (there are three different boxes that ask for the year, month and date of their birth). Is there a way I can convert these input strings into a date format that I can then use to find the days between today's date and their next birthday?
Thanks and sorry if this is a stupid question!

Remember in JS that months are indexed from 0, so January === 0.
var date = new Date('2017','5','25'); would be today, assume you have something like:
var userDd = '25';
var userMm = '6'; // User doesn't know the months are indexed at 0.
var userYy = '2017';
var date = new Date(userYy, userMm - 1, userYy);
date.getTime(); // returns the milliseconds value.

Related

How do I check if the time between two dates exceeds a certain number of months?

I have an app where a user can select two dates (a from date and a to date) and the time between the dates should not exceed 4 months. A user can select the day, month and year for each date. Is there some kind of logic I could use to achieve this, so that an error is returned if the date range is over 4 months. Each input as an integer. For example, a start date of March 31st 2019 would be: from_date_day = 31 from_date_month = 3 and from_date_year = 2019
For example, I something like this would kind of work:
((Math.abs($('#to_date_month').val() - $('#from_date_month').val()) > 2) && $('#from_date_day').val() <= $('#to_date_day').val()
return "error"
The problem with this code is that it doesn't work when the dates straddle two different years. I'm using coffeescript, but a solution in jquery or js would also work.
I'd recommend creating two Javascript Date objects of those two dates. This can be done by feeding the year, the month and finally the day to the constructor of the Date object.
e.g.
var startDate = new Date(2019, 1, 16); // January the 16th
var endDate = new Date(2019, 3, 30); // March the 30th
Using the .getTime() function of the Date object you can get the number of milliseconds passed since 1.1.1970. If you calculate the difference between those two numbers, wrap it inside Math.abs() and divide that number by 1000, 60, 60 and finally 24 you get the number of days. If this number is bigger than ~120, the range is more than four months.
console.log(Math.abs(startDate.getTime() - endDate.getTime()) / 1000/60/60/24);
In your use case the Date object could be set like this:
var startDate = new Date(parseInt($('#from_date_year').val()), parseInt($('#from_date_month').val()), parseInt($('#from_date_day').val()));

Javascript For Display Previous Day From Given Date [duplicate]

This question already has answers here:
Add one day to date in javascript
(11 answers)
Closed 4 years ago.
I have From-Date, To-Date, and Total-Days...if i have a From-Date and Total-Days then i have to calculate To-Date automatically
I Used The Following method to get the To-Date day
var FromDate = $("#FromDate").val();
var TotalDays = $("#txtDays").val();
FromDate.setDate(parseInt(FromDate.getDate()) + parseInt(NoOfDays));
var dd = FromDate.getDate()-1;
This Will Not Work For Day 1 of every month.....Since It Returns 0
How To Handle This Situation or help me to solve this in another way....Thanx In Advance
try this
var d = new Date('08-20-2018');
d.setDate(d.getDate() - 1);
alert(d.getDate());
Date object is smart enough to know what to do if you set any of the "components" (month, day, hour, minute, second, millisecond) outside of "normal" range - it does the maths for you
If you only need to know the previous date, you can always subtract the 24hours from the epoch time and then convert it back to date object and get the date like:
new Date(new Date('08-01-2018').getTime() - 24*3600000).getDate()
new Date('08-01-2018').getTime() will give you the epoch time of the date you want previous date from
24*3600000 is subtracting the 24 milliseconds from the epoch
After subtracting the value you get the previous day epoch and using the new Date() constructor you are getting the Date object again
On this new date object you can call getDate() method to get the correct result of 31.
I have given date to Date constructor in MM-DD-YYYY format

How the .getTime() can preserve the original date dd/MM/yyyy?

I have a trouble. I have an angular Javascript application that is storing the dates in mysql with milliseconds, but in some moments the date is interpreted with one more or less day. For example:
If the user selects in the date picker: 03/02/2017, the application is saving this (in milliseconds) as 02/02/2017 or 04/02/2017. I believe it is due to the timezone. This is the way I'm using to convert the date in milliseconds:
var temp = $("#datetimeField").val().split("/");
var newDatetime = new Date(temp[2], temp[1] - 1, temp[0]).getTime();
As you can see, I know the day, the month and the year before store it in the database. Normally the date is stored and works well, but in some moment the date changes as I showed above. How can I always get temp[2]/temp[1]-1/temp[0] ??? from the stored milliseconds?

Using javascript to perform some date calculations/comparisons

I have a Date object and I'm trying to add a year to the today's date. I also have to have a way to compare the date that's in the date object (newly made + one year) and today's date. How do I compare today's date with the date in the variable? The point is, I need to have a way to know if today's date is the same or greater to the expiration date, that way I could redirect users to a different location... thanks all!
here's my Date object
var expDate = new Date();
The basic JavaScript Date object has stuff built in to handle all of that natively.
For adding a year to your date simply do this:
var currentDate = new Date();
var futureDate = new Date(currentDate);
futureDate.setFullYear(futureDate.getFullYear() + 1);
That gets the current day as the date, and then creates a new date, based on today's date and sets the yea to the current year plus 1.
As for the comparison, simply use <, <=, >, >=, ==, and !=. JavaScript understands what to do with those operators when Date objects are involved and will compare the two dates appropriately.
On thing that I might suggest doing (since you only care about the actual date, and not the time element of the Date object, is add in this line of code after getting today's date:
currentDate.setHours(0, 0, 0, 0);
That will set the hour, minute, second, and millisecond values to 0, so that only the date is a factor when doing any comparisons.
For everything that you could ever need to know about the JavaScript Date object, check out here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Edit: Fixed syntax issue.

Comparing today's date with another date in moment is returning the wrong date, why?

I'm using moment.js 1.7.0 to try and compare today's date with another date but the diff function is saying they are 1 day apart for some reason.
code:
var releaseDate = moment("2012-09-25");
var now = moment(); //Today is 2012-09-25, same as releaseDate
console.log("RELEASE: " + releaseDate.format("YYYY-MM-DD"));
console.log("NOW: " + now.format("YYYY-MM-DD"));
console.log("DIFF: " + now.diff(releaseDate, 'days'));
console:
RELEASE: 2012-09-25
NOW: 2012-09-25
DIFF: 1
Ideas?
Based on the documentation (and brief testing), moment.js creates wrappers around date objects. The statement:
var now = moment();
creates a "moment" object that at its heart has a new Date object created as if by new Date(), so hours, minutes and seconds will be set to the current time.
The statement:
var releaseDate = moment("2012-09-25");
creates a moment object that at its heart has a new Date object created as if by new Date(2012, 8, 25) where the hours, minutes and seconds will all be set to zero for the local time zone.
moment.diff returns a value based on a the rounded difference in ms between the two dates. To see the full value, pass true as the third parameter:
now.diff(releaseDate, 'days', true)
------------------------------^
So it will depend on the time of day when the code is run and the local time zone whether now.diff(releaseDate, 'days') is zero or one, even when run on the same local date.
If you want to compare just dates, then use:
var now = moment().startOf('day');
which will set the time to 00:00:00 in the local time zone.
RobG's answer is correct for the question, so this answer is just for those searching how to compare dates in momentjs.
I attempted to use startOf('day') like mentioned above:
var compare = moment(dateA).startOf('day') === moment(dateB).startOf('day');
This did not work for me.
I had to use isSame:
var compare = moment(dateA).isSame(dateB, 'day');

Categories