Calculate date difference in integer value - javascript

I have two date fields with IDs gp_vdate_from and gp_vdate_to. And I have a hidden div which is populated by a dynamic table. The div gets visible on click of a button after entering date fields. I did something like this to calculate the date difference
function parseDate(str) {
var mdy = str.split('-')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daydiff(first, second) {
return Math.floor((second-first)/(1000*60*60*24))
}
var diff=(daydiff(parseDate($('#gp_vdate_from').val()), parseDate($('#gp_vdate_to').val())));
The date entered is in the format 10-2-2012.
But I am not able to give to get the difference? Can someone point out why?

I think you do not have valid dates. Look at this line:
new Date(mdy[2], mdy[0]-1, mdy[1])
This is like writing
new Date(2012,9,'feb')
for 10-feb-2012, which is not valid. The date constructor takes arguments like this:
new Date(year, month, day [, hour, minute, second, millisecond ]);
Where all the arguments are integers ('feb' is not valid, also you were passing arguments in the wrong order.)
So I think you need to look at your parseDate method.
This is all assuming that JQuery doesn't change how the Date object works - you may need to check that.
You should use a javascript console like Firebug for firefox to help you debug.

You can use date.getTime() to check the difference
function daydiff(first, second) {
return Math.floor((second.getTime()-first.getTime())/(1000*60*60*24));
}
please check with Date object create arguments
new Date(year,month,day);

You could try using date.js, a small but awesome JS library just for working with dates. It normalises Date objects across browsers and gives all kinds of sugary methods for working with dates :)
Can be used with jQuery too
EDIT
date.js makes working with dates less painful, but is not essential, everything you need can be done in pure JS.
Other answerers - Actually, the Date constructor in JavaScript can accept a single string as an argument, which it uses to generate a new Date object.
I made a fiddle based on your example code showing how to calculate number of days between two dates. Have a look and play around and it might be what you need :)

Related

add future date to a date gotten from json response

I have a date gotten from json response. I able to filter the date to confirm that it is actual date type but I am not able to set future date to it. Below is my snippet
$rootScope.until= response.data.data.dateReceived;
//return future date
// var targetDate = new Date();
$rootScope.until.setDate($rootScope.until + 60);//adding 60 days but cannot
// So you can see the date we have created
$rootScope.until = $filter("date") ($rootScope.until), 'EEEE, MMMM d, y');
Please how can I add future dates
There seem to be two different mistakes here.
You're trying to use Date functions on a Number.
The function Date#setDate() takes as its argument the day of a
month, not the timestamp itself.
Date vs. Number
Problem
If you used new Date(response.data.data.dateReceived) to convert the number of milliseconds you received into a Date datatype, you would be able to access methods like setDate().
However, with your current code, you're trying to perform setDate() on what — to JavaScript — is just an ordinary number. It might as well be -1, since JavaScript has no idea that your number means anything more than its numeric value.
Solution
Since your input data is in milliseconds (a fact you indicated in the comments), the easiest way to accomplish this would simply be to add milliseconds to your initial timestamp like so:
const SIXTY_DAYS = 5184e6; //1000ms/sec * 3600secs/hour * 24hours/day * 60days
$rootScope.until= response.data.data.dateReceived + SIXTY_DAYS;
Just make sure that the value is a number, not a string, otherwise this will perform concatenation instead of addition.
setDate arguments
Problem
If you do have a variable with a datatype of Date (see above), you would have access to methods like Date.setDate(). However, this method's arguments are a bit different than what your code assumes.
Solution
setDate() takes in as its argument a number of days since the start of the month. If you want to add a number of days, you could do the following:
$rootScope.until= new Date(response.data.data.dateReceived);
$rootScope.until.setDate($rootScope.until.getDate() + 60);
This code will obtain the day of the month for the date, then add 60 days to that value. It will automatically handle the change in the month.

how to convert javascript date according to a new timezone

I thought I had a handle on this, but I cant work it out.
scenario:
1) user selects a date widget which passes back a date in local timezone, lets say 10am 'Australia/Sydney'
2) user then selects a timezone that is different, by identifier 'Australia/Brisbane' (this is a different TZ and may have daylight saving etc...) lets assume its +1hr
What I want to do is have a function that takes a Date object that represents [10am 'Australia/Sydney'] and return to me a new Date that represents [10am 'Australia/Brisbane] i.e. the underlying UTC time will have shifted +1hr
function convertToTimezone(date, newTimezone) {
... what goes here? ...
return newDate;
}
Ive been mucking about with moment timezone and I cant get it to do what I want.
The moment-timezone library should make this trivial:
function convertToTimezone(date, newTimezone) {
return moment(date).tz(newTimezone);
}
Or if date is already a moment:
function convertToTimezone(date, newTimezone) {
return date.clone().tz(newTimezone);
}
See the documentation on Converting to Zone for more information.
OK, FWIW, I got an answer myself. moment.tz doesnt work as I imagined.
To summarise, I want to take a javascript Date that has a wallclock time, say '10am on the 15 sep 2018' that has been associated with a certain timezone identifier, say BrisabneOz.
And turn it into a new date that represents that same wallclock time, but in a different timezone. In otherwords, change the underlying UTC time by the amount required by the shift in timezones and/or daylight savings etc...
The way I found to do this was to get the string of the wallclock date, thus stripping any associated timezone from tbe equation, and using moment.tz to make another date object using the new different timezone. Which it can do.
The part that confused me was having to go to a string as a step - thought I could just pass in one date and get moment.tz to magic me up another date ala #Alex Taylor answer, but this doesnt actually work.
function convertDateToTimezone(date, timezone) {
const str = moment(date).format('YYYY-MM-DD HH:mm:ss');
const tzMoment = moment.tz(str, timezone.identifier)
return tzMoment.toDate()
}

How do I format a Javascript date like 1950-12-30T18:25:43.511Z

I have an API where I the date need to be formatted like this
1950-12-30T18:25:43.511Z
This format looks somewhat unfamiliar to me, and I'm wondering how I can take a format like this
1950-12-30
and turn it into something like the former. FYI I'm using javascript (express)
You are trying to put the date into ISO format and the native Date object will do that for you, fairly simply, with the .toISOString() method:
var newDate = new Date("0977-03-28");
console.log(newDate.toISOString());
The result of that is: 0977-03-28T00:00:00.000Z (look familiar? :D )
One issue that you will have (if it is an issue), is that, because you only have the date value, and not a time value, the last part of the string will always be T00:00:00.000Z (which is the "time" section of the Date). You'll see that if you use today's date, using var newDate = new Date(); (which captures this instant), the time will be filled in: 2015-02-19T16:50:18.078Z (at the time of testing)
For more information, see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
(Note: in IE, this only works in v9 or later, though, that link also has a polyfill for older IE versions)

Validating a UK date using Javascript/jQuery

I have two jQuery datepickers that once changed, will trigger some ajax to grab all information between the two dates.
I want to run some code to check that the first date is smaller than the second, by converting to a date using this code:
function FormatUkDate(dateStr) {
dateStr = dateStr.split("/");
return new Date(dateStr[2], dateStr[1] - 1, dateStr[0]);
}
This works great, but the problem is even if I enter a date of '50/08/2011' it still validates and converts that to a Javascript date, I believe by adding the additional number of days to the start date.
Is there a way to properly validate this please?
Thanks!
you can validate using a jquery masked plugin,you can check it http://digitalbush.com/projects/masked-input-plugin/
For working with dates you can try to use datejs library. It has many features including validating dates. To solve your problem you can use Date.validateDay method. Also you can use datejs to compare dates.
hm... I guess a plugin would be a better solution, but for what it's worth:
function FormatUkDate(dateStr) {
dateStr = dateStr.split("/");
var newDate = new Date(dateStr[2], dateStr[1] - 1, dateStr[0]);
return newDate.getDate() == Number(dateStr[0]) && newDate.getMonth() == Number(dateStr[1]) - 1? newDate : null;
}
returns null if the date carries over to the next month.
Edit
New code :P

Convert from string with milliseconds to date object Javascript

I got this problem when dealing with date time conversion. I have timestamp data from postgreSQL database with format like this one
"2011-04-04 19:27:39.92034"
In order to display it in highcharts, I have to convert it to date or time object. Without milliseconds, I easily convert it with Date.js
But milliseconds can't be handled with that library. I tried also with Date.parse but always got NaN.
Any solution for this problem? Thank you
JS built in Date class should be able to handle this, and getTime() can return milliseconds since start 1970 (UNIX time). Watch out for time zone issues though; the constructor may interpret the date/time as being local, but getTime()'s milliseconds since 1970 may be in UTC, baking in a conversion that is difficult to remove.
new Date("2011-04-04 19:27:39.92034").getTime()
1301941659920
Many ways to Rome. The given code will return '(datestr=) 2011-4-4 19:27:39.92'. Is that what you look for?
var darr = '2011-04-04 19:27:39.92034'.split('.')
, dat=new Date(darr[0])
, datestr = '';
dat.setMilliseconds(Math.round(darr[1]/1000));
datestr = [ [dat.getFullYear(),dat.getMonth()+1,dat.getDate()].join('-')
,' ',
[dat.getHours(),dat.getMinutes(),dat.getSeconds()].join(':')
,'.',
dat.getMilliseconds()
].join('');
Can't you just cut of the last 6 chars of that string? You might then round the miliseconds and eventually add a second to you time object.
This is simpler and in one line:
new Date('01/09/2015 06:16:14.123'.split(".")[0])

Categories

Resources