Javascript need two date instances Keep getting references instead - javascript

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.

Related

Set Hours in Date() to 0 [duplicate]

i am trying to get current date to compare and setting hours to zero but still getting time.
var today = new Date(new Date().setHours(0,0,0,0));
var todaynew = today.toISOString();
console.log(todaynew);
my output like :
2018-03-20T18:30:00.000Z
I need to get date as it is but time 2018-03-20T00:00:00.000Z
When you create a new Date(), the time zone is that of the system. When you use toISOString(), the time is printed in UTC. This means that your code will print a different result when running on systems with different time zones (it prints 2018-03-20T23:00:00.000Z for me).
Instead of using setHours(), use setUTCHours().
var today = new Date(new Date().setUTCHours(0,0,0,0));
var todaynew = today.toISOString();
console.log(todaynew);

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

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

Milliseconds for current date in javascript

When I try the following
new Date().valueOf()
the result is 140082670954. For
new Date('05/23/2014').valueOf()
the result is 1400783400000.
There is a difference in the millisecond outputs. The second one is at 00:00:00 hrs but the first one is at 12pm with todays date.
I need to get the milliseconds as in the second one. How would I do this dynamically?
When you do:
new Date()
a new Date object is created with a time value for the current instant. When you do:
new Date('05/23/2014')
a new Date object is created at 00:00:00.000 on the specified date. If you want the equivalent using the constructor, then create the Date and set the time appropriately:
var d = new Date();
d.setHours(0,0,0,0);
NB
Please don't pass strings to the Date constructor. It calls Date.parse which is largely implementation dependent and inconsistent across browsers (even using the string format specified in ES5). Call the constructor with the required values:
new Date(2014, 4, 23);
noting that months are zero indexed so May is 4.
I take it that you want the milliseconds from midnight of a given day? I am afraid it won't be too simple, thanks to JavaScript's very constrained date-time API. You can extract the year, month, and day from the date object and create a new object from those:
var now = new Date();
var day = now.getDate();
var month = now.getMonth();
var year = now.getFullYear();
var today = new Date(year, month, day);
var millis = today.valueOf();
BTW: You mention that the first one "is at 12pm" - that depends on at what time you execute the statement. new Date() gives you the date including the current local time. So it appears that you tried it at roughly 12pm :-)

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

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