setDate() is using current date as basis instead of desired object - javascript

I'm trying to add days to a Date object, but the output is not as desired:
// THIS IS JUST A SIMPLIFIED EXAMPLE.
let date = new Date("2019-01-01 00:00:00")
let finalDate = new Date()
finalDate.setDate(date.getDate() + 10)
console.log(finalDate)
Desired output:
11/01/2019 00:00:00
Actual output:
31/08/2019 13:06:30
It's using the current system date as a base and setting it to finalDate. which is not what I'm looking for.

The way you were declaring your literal date was in error. Also, you're better passing the existing date as a parameter to the constructor for the second one.
let date = new Date("2019-01-01 00:00:00");
let finalDate = new Date(date);
finalDate.setDate(date.getDate() + 10);
console.log(finalDate)

If your desired output is 11/01/2019 then you need to change a few things in how you're calculating your dates.
Here's code that get you what you're looking for:
let date = new Date('2019/01/01 00:00:00');
let finalDate = date;
finalDate.setMonth(date.getMonth() + 10);
console.log(finalDate);
Notice that for finalDate, I'm not setting it to a new instance of a date, but rather assigning it the value of the date variable. This way the two are the exact same date and allows us to begin adding months to the one we wish to add months to. Otherwise the days may not come out the same by initializing finalDate as its own separate date object.
Also notice that I'm calling getMonth rather than getDate, since we're adding months strictly.
Here is a working jsfiddle of your desired results:
https://jsfiddle.net/yzmk61xf/#&togetherjs=sSETlrppq6

Related

String dates comparison in javascript

So, I have two variables and one function:
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
const dateToCompare=moment.utc(endDate).format('DD-MM-YYYY')
const maximum=moment.utc(addDays(new Date(),14)).format('DD-MM-YYYY')
However, I do not know how to compare them, since they are now formatted as strings, but at the same time new Date(dateToCompare) doesn't work.
Can someone give me a hint?
Why are you using built–in methods to add days when you are using moment.js? Consider:
let maximum = moment.utc().add('day',14).format('DD-MM-YYYY')
To set a date to the start of a day, use the moment.js startOf method:
let maximum = moment.utc().add('day',14).startOf('day')
let dateToCompare = moment.utc(endDate).startOf('day')
You can compare the dates as strings if formatted as YYYY-MM-DD, or just leave them as moment objects and compare those using isSame, isAfter, isSameOrBefore, etc.
When parsing strings as in:
const dateToCompare=moment.utc(endDate)
you should always pass the format to parse unless endDate is a Date or moment object. new Date(dateToCompare) doesn't work because Why does Date.parse give incorrect results?
If what you're trying to do is strip out the time and just compare the dates, don't do a string conversion; just set the hour, minutes, and seconds on your Date objects to zero before making your date comparison.
let foo = new Date();
console.log(foo);// date includes time
foo.setHours(0); foo.setMinutes(0); foo.setSeconds(0);
console.log(foo) // date set to midnight (in your timezone)

How to add days to current date in angular

Using this:
var myDate = new Date(new Date().getTime()+(5*24*60*60*1000));
I get a date and time like this 2018-12-30T14:15:08.226Z, but only i want is this 2018-12-30. How can I retrieve just the date?
**This is Fixed. Thank You everyone who helps!!!
You're experiencing a JS problem, it has nothing to do with Angular.
This will use Date methods to get all the data you want:
const date = new Date ();
let dateString = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
// 2018-12-26
You can take advantage of the fact that the ISO 8601 format (what you are getting by implicitely converting to string) is well-codified with a separator T between the date and time in order to split it.
toISOString() gives you what you're seeing. split("T") splits the string into an array of strings with T as separator. [0] then extracts the first element.
var myDate = new Date(new Date().getTime()+(5*24*60*60*1000));
console.log(myDate.toISOString().split("T")[0]);

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');

Javascript need two date instances Keep getting references instead

How to have a date and subtract 1 year and have a second date for use in display and caculations?
I'm a newbe with JS and find myself fighting the date object
I have declared both currentDate and purchaseDate As var new date() in the globals area
But now in a function I try to assign the Original date as "currentDate and the purchaseDate" as one year later,, The alert shows that I have changed the vaue of currentDate rather than just the value of purchaseDate as I intended..
Not what I want! So I get pass by reference vs by value but don't know how to get this so that I have two separate values for the currentDate and the purchaseDate (one year earlier)
currentDate = data.getValue(0,2);
purchaseDate = valueOf(data.getValue(0,2));
purchaseDate.setFullYear(purchaseDate.getFullYear()-1);
alert(purchaseDate);
so this code fails also; That is,, purchase date is 1 year back but so is current date
currentDate = data.getValue(0,2);
purchaseDate = data.getValue(0,2);
purchaseDate.setFullYear(purchaseDate.getFullYear()-1);
alert(purchaseDate);
The code which you posted is too ambiguous to reliably point the root cause of your problem (it's unclear what valueOf() is doing), but basically, you indeed need to create a new Date instance based on the time of the other Date. Here's how you could do this, assuming that currentDate is a real Date as well.
var purchaseDate = new Date(currentDate.getTime());
Here's a full kickoff example:
var currentDate = new Date();
var purchaseDate = new Date(currentDate.getTime());
purchaseDate.setFullYear(purchaseDate.getFullYear() - 1);
alert(currentDate); // Today.
alert(purchaseDate); // Today minus one year.

How to create object of Date("23.03.2010")

I have astring directly coming form the database and I am creating object of Date as
Date dt=Date("23.03.2010") and it is comin NaN
whereas when I use Date dt= Date("03/23/2010") it works fine.
Any Idea how I can get this working?.
You can parse the string from the database and then create the date object. You will have to subtract 1 from the parsed month value to get a correct date.
var dateString = "23.03.2010";
var dateParts = dateString.split(".");
var dt = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
You must pass string (parsed) dates in MDY format. This is to prevent ambiguity (does 5/6/2010 mean 6th May or 5th June?)
If you prefer, you can use new Date(year, month, day) format, and pass the arguments separately.
The safest way if is you can return the date as milliseconds since 1970-01-01, then you can easily create a Date object from it. Example:
var n = 1269302400000;
var dt = new Date(n);
Note that you'll want to invoke Date with the new operator - from the Mozilla Developer Center:
Invoking Date in a non-constructor
context (i.e., without the new
operator) will return a string
representing the current time.
The same page details the syntax of the Date constructor.
If you are constructing a Date from a string the format accepted is governed by the rules of the Date.parse method. See Microsoft's Date.parse documentation for a summary of these rules.
Give this a try...
var dateParts = '23.03.2010'.split('.');
// -1 from month because javascript months are 0-based
var dateObj = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
try
d="23.03.2010".split(".");
Date dt=Date([d[1],d[0],d[2]].join("/"))
i think it isn't the most beautiful way.

Categories