JAVASCRIPT validator is not working properly [duplicate] - javascript

I want to do same thing as
How do I get the number of days between two dates in JavaScript?
but I want do the same on this date format: 2000-12-31.

function daysBetween(date1String, date2String){
var d1 = new Date(date1String);
var d2 = new Date(date2String);
return (d2-d1)/(1000*3600*24);
}
console.log( daysBetween('2000-12-31', '2005-05-04') ); //-> 1585
ISO8601 date strings are recognized by JavaScript directly. No need to parse them yourself.

Try this.
var toDate = "2000-12-31";
var fromDate = "2000-10-30";
var diff = Math.floor(( Date.parse(toDate) - Date.parse(fromDate) ) / 86400000);
You wont be asking this question if you have checked the answer with more up-votes and not the marked answer on the link you have provided. :)

Well, it's not jQuery, but just as easy to work with. Check out DateJS. Can parse dates, differences, and more.

The other solutions here do not take into account the TimeZone information (which is fine if that is what you want)
but I came across a problem like this: I have two dates:
Thu Mar 01 2012 00:00:00 GMT+0100 and Sat Mar 31 2012 00:00:00 GMT+0200
which will give you 29.95833 days before the Math.floor and hence 29 days after the floor.
This is not the 30 days I was expecting. Clearly Daylight Saving has kicked in and shortened
one of the days by an hour.
Here is my solution which takes TimeZones into account:
function daysBetween(date1String, date2String) {
var ONE_DAY = 1000 * 60 * 60 * 24;
var ONE_MINUTE = 1000 * 60;
var d1 = new Date(date1String);
var d2 = new Date(date2String);
var d1_ms = d1.getTime() - d1.getTimezoneOffset() * ONE_MINUTE;
var d2_ms = d2.getTime() - d2.getTimezoneOffset() * ONE_MINUTE;
return Math.floor(d1_ms - d2_ms/ONE_DAY);
}

Related

Difference between two dates in hrs and mins

I have two dates in millis 1513885098821 & 1513885078742.
How to display the difference between above two dates in hrs and mins like 2 hrs 31 mins.
If moment have any option then its good, solution using plain javascript is also ok for me.
I tried below
moment(new Date(txn.toDate - txn.fromDate)).format('HH mm')
But it gives 05 30 result. Output of below line is
new Date(1513885098821 - 1513885078742);
result: Thu Jan 01 1970 05:30:20 GMT+0530 (India Standard Time)
There are probably countless answers already to help you find the difference between two dates, either using moment js or simply the native javascript Date object. Since you are having difficulty though, here is an example using moment js and its diff function:
// use timestamps to create moment objects
const startDate = moment.utc(1513885098821);
const endDate = moment.utc(1513885078742);
const hourDiff = startDate.diff(endDate, 'hours');
console.log(hourDiff); // 0
const minuteDiff = startDate.diff(endDate, 'minutes');
console.log(minuteDiff); // 0
const secondDiff = startDate.diff(endDate, 'seconds');
console.log(secondDiff); // 20
console.log(`${hourDiff}hrs ${minuteDiff}mins ${secondDiff}sec`); // 0hrs 0mins 20sec
Or try it online here.
You don't need to use Date, just do this:
prettyMillisDiff(millis1, millis2) {
let minDiff = (millis1 - millis2)/60000;
if (minDiff < 0) {
minDiff *= -1;
}
const hours = Math.floor(minDiff/60);
const mins = Math.floor(minDiff%60);
console.log(`${hours} hours ${mins} mins`);
}
try splitting string from the first method.
var k=moment(new Date(txn.toDate - txn.fromDate)).format('HH mm');
var frmt=k.split(' ');
var min=frmt+'mm';
var hr=frmt+'fr';

JavaScript setHours() and getHours() [duplicate]

I am trying to subtract hours from a given date time string using javascript.
My code is like:
var cbTime = new Date();
cbTime = selectedTime.setHours(-5.5);
Where selectedTime is the given time (time that i pass as parameter).
So suppose selectedTime is Tue Sep 16 19:15:16 UTC+0530 2014
Ans I get is : 1410875116995
I want answer in datetime format.
Am I doing something wrong here? Or there is some other solution?
The reason is that setHours(), setMinutes(), etc, take an Integer as a parameter. From the docs:
...
The setMinutes() method sets the minutes for a specified date
according to local time.
...
Parameters:
An integer between 0 and 59, representing the minutes.
So, you could do this:
var selectedTime = new Date(),
cbTime = new Date();
cbTime.setHours(selectedTime.getHours() - 5);
cbTime.setMinutes(selectedTime.getMinutes() - 30);
document.write('cbTime: ' + cbTime);
document.write('<br>');
document.write('selectedTime: ' + selectedTime);
Well first off setting the hours to -5.5 is nonsensical, the code will truncate to an integer (-5) and then take that as "five hours before midnight", which is 7PM yesterday.
Second, setHours (and other functions like it) modify the Date object (try console.log(cbTime)) and return the timestamp (number of milliseconds since the epoch).
You should not rely on the output format of the browser converting the Date object to a string for you, and should instead use get*() functions to format it yourself.
According to this:
http://www.w3schools.com/jsref/jsref_sethours.asp
You'll get "Milliseconds between the date object and midnight January 1 1970" as a return value of setHours.
Perhaps you're looking for this:
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_sethours3
Edit:
If you want to subtract 5.5 hours, first you have to subtract 5 hours, then 30 minutes. Optionally you can convert 5.5 hours to 330 minutes and subtract them like this:
var d = new Date();
d.setMinutes(d.getMinutes() - 330);
document.getElementById("demo").innerHTML = d;
Use:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();
try this:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();

Chrome can't parse date but IE can

I'm having trouble parsing dates for my website. It used to work fine on both IE and Chrome (I haven't tried Firefox yet). But recently I have been unable to parse dates on chrome.
The date string which I obtain from the database looks like this "Oct 17 2016 12:00AM"
Here is the code I'm using to debug my problem
console.log("String = "+item.DueDate);
console.log("new Date = " + new Date(item.DueDate));
console.log("Date Parse = " + Date.parse(item.DueDate));
console.log("Moment Parse = " + moment(item.DueDate));
Here is what is returned by IE:
String = Oct 17 2016 12:00AM
new Date = Mon Oct 17 2016 00:00:00 GMT-0400 (Eastern Daylight Time)
Date Parse = 1476676800000
Moment Parse = 1476676800000
And here is what is returned by Chrome:
String = Oct 17 2016 12:00AM
new Date = Invalid Date
Date Parse = NaN
Moment Parse = NaN
I use Date.parse() in one of my function that finds the difference between to dates:
function daydiff(first, second) {
return Math.round((second - first) / (1000 * 60 * 60 * 24));
}
var dif = daydiff(Date.parse(item.DueDate), Date.parse(item.DateShipped));
What should I do to my date string in order for it to work with both chrome and internet explorer?
Fixed
So I fixed it by changing my web api call to return a DateTime rather than string.
Never parse strings with the Date constructor (or Date.parse, they are equivalent for parsing) as it is almost entirely implementation dependent. Even the one format specified in ECMA-262 is not reliably parsed by all browsers in use.
Use a bespoke function or a library that provides parsing and formatting and always pass the format to parse to the parser. Suitable libraries are moment.js, date.js and fecha.js, but there are many others.
A bespoke function might look like:
function parseSpecia(s) {
var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};
var h;
if (/a[mp]$/i.test(s)) {
h = /am$/i.test(s)? 0 : 12;
s = s.replace(/a[mp]$/i,'');
}
var b = s.split(/[ :]/)
return new Date(b[2], months[b[0].toLowerCase().substr(0,3)], b[1],(b[3]%12)+h, b[4]);
}
var s = 'Oct 17 2016 12:00AM';
console.log(parseSpecia(s));
Whereas using a library would look like:
fecha.parse('Oct 17 2016 12:00AM','MMM DD YYYY hh:mm:zz');

Comparing two dates in different timezones

I'm comparing two dates; one returned as a UTC String (as part of an Ajax response) and the second in local browser time:
Basically, I want to see if the date returned (endTime) happened before right now. My code is below and I thought I had it right but it's not working.
var isActive = true;
var buffer = 30000; // 30 seconds
var endTime = new Date(Date.parse(response.endTime)); // Fri Oct 23 2015 12:01:14 GMT-0400 (EDT)
var now = new Date(); // Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)
var nowUtc = new Date(now).toUTCString(); // "Fri, 23 Oct 2015 00:01:31 GMT"
var nowTimeMs = new Date(nowUtc).getTime(); // 1445558491000
var endTimeMs = endTime.getTime() + buffer; // 1445616104000
if( nowTimeMs > endTimeMs ){
isActive = false;
}
isActive should remain as true but instead it's false. I feel like I've been looking at this too long and am missing something very simple. Am I?
Thanks for any helpful tips.
Update:
Based on the responses I thought I'd update my question. What is the best way to compare two dates where one is this:
new Date(); // Thu Oct 22 2015 21:51:53 GMT-0400 (EDT)
...and the other is a String representation of date:
"2015-10-23 01:49:27"
I figure the best way to create a valid Date object out of the String is using this code.
isThisActive:function(p){
var isActive = true;
var buffer = 30000;
var pEndTime = myObj.parseStringAsDate(p.callEndTime);
var now = new Date();
var offset = now.getTimezoneOffset() * 60000;
now.setTime( now.getTime() + offset );
var nowTimeMs = now.getTime();
var endTimeMs = pEndTime.getTime() + buffer;
if( nowTimeMs > endTimeMs ){
isActive = false;
}
return isActive;
},
parseStringAsDate:function(str){
var dateTimeStr = str.split(" ");
var dateStr = dateTimeStr[0].split("-");
var year = dateStr[0];
var month = dateStr[1];
var day = dateStr[2];
var timeStr = dateTimeStr[1].split(":");
var hours = timeStr[0];
var minutes = timeStr[1];
var seconds = timeStr[2];
return new Date( year,month,day,hours,minutes,seconds);
}
Because "pEndTime" is in UTC I applied the offset to the "now" Date object but even this is not working. Where's the problem here? I thought this would solve it.
SOLVED:
The latest code I posted did work. I was just getting incorrect values for the response.endTime (It wasn't converted to correct military time). Thank you everyone for your input. I've tried to upgrade as many helpful responses as I could.
You should not use the Date constructor or Date.parse (which do the same thing) to parse date strings. Either write your own parse function (below) or use a well maintained library.
To parse the format in the OP, you can use:
// Parse Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)
function parseMMMDY(s) {
var b = s.split(/\W/);
var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};
var sign = /GMT-\d{4}/i.test(s)? 1 : -1;
var min = +b[5] + (sign * b[8].slice(0,2) * 60 ) + (sign * b[8].slice(-2));
return new Date(Date.UTC(b[3], months[b[1].toLowerCase().slice(0,3)], b[2], b[4], min, b[6]));
}
document.write(parseMMMDY('Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)'));
I think the problem is here:
var endTime = new Date(Date.parse(response.endTime));
respnonse.endTime is UTC, right? But when you parse it to Date value, Date.parse assumes it is in local timezone (GMT-0400 as in your example code). It means that the endDate gets the wrong value
I usually use moment.js in my projects which related to formatting date time, especially in the reports (I'm working in the field of finance). You must have one more library in your project but it provides many other functionalities
Sorry, this is for your new update. I haven't got enough 'population' to leave a comment :P
var endTime = new Date(Date.parse(response.endTime)); // Fri Oct 23 2015 12:01:14 GMT-0400 (EDT)
var now = new Date(); // Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)
Your endTime doesn't seem to return a UTC date as you mentioned. It looks to be using (EDT) so maybe you didn't have to convert it to UTC.

Convert dd-mm-yy to javascript date object

I get a date which comes in this format: ddmmyy, and I need to do some validation with it.
How can I parse it to a javascript date object?
I've tried to search, and there are a lot on the ddmmyyyy format, but not the format I get.
EDIT: Example date: 031290 = 3.12.1990.
You could parse ddmmyyyy into a yyyy-mm-dd form and pass that to Date.parse.
Date.parse( "02032002".replace(/^(\d\d)(\d\d)(\d{4})$/, "$3-$2-$1") );
Or otherwise split it up and use the Date's setters / constructor:
// month - 1 : in this form January is 0, December is 11
var date = new Date( year, month - 1, date );
Just noticed the YY vs YYYY part of the question:
var parts = /^(\d\d)(\d\d)(\d{2})$/.exec( "190304" );
var date = new Date( parts[3], parts[2]-1, parts[1] );
You could augment that with some code which adds a 20 or 19 depending if the year is over or below a certain threshold (like 70 : < 70 indicates 20xx and >= 70 indictaes 19xx years).
Try this:
var a="221178".split(/(?=(?:..)*$)/);
var result=new Date ( parseInt(a[2],10) + 1900 , a[1]-1 , a[0] )
result:
Tue Nov 22 1978 00:00:00 GMT+0200
JSBIN
If you want a non-regex solution, you can use new Date(year, month, date) constructor, and simple cut strings into those parts. It's not fancy, but it clear in what it does:
function parse2date(str){
var year = parseInt(str.substr(4, 2));
var month = parseInt(str.substr(2, 2));
var day = parseInt(str.substr(0, 2))
return new Date(year < 20 ? 2000 + year : year, month - 1, day)
}
this function assumes if 2-disgit years is below 20 - then it is meant to be in 2000s, otherwise it's in 1900s. But you can adjust the limit. Try calling it:
alert(parse2date('031290'));
Ok, so here is how I solved it.
The answers here is right, except I wasn't happy with the way the detection of the current century worked; so I basically did this:
var date = new Date(year + 2000, month - 1, day);
if (date > new Date())
date.setYear(year + 1900);
With this code, I can maximum validate an age of 100, but that shouldn't be a problem.
Mukul Goel in the comment below points out it can only validate dates in the future. Probably right, I haven't checked it myself.

Categories