Date comparison getting error - javascript

we stuck date comparison, we tried the below code. EndDate value is related to jan 21, 2016 but in alert showing showing Fri Sep 01 2017 10:10:10 GMT+0530 (India Standard Time), could you please share me your ideas
var endDateVal = "21/01/2016 10:10:10".replace(/-/gi, "/");
alert(new Date(endDateVal));
if (new Date(endDateVal) > new Date()) {
alert("Last end date should be minor than today");
}
Fiddle

The date is formatted incorrectly. The date needs to be an ISO 8601 or IETF-compliant RFC 2822 formatted date, like:
2016-01-21T10:10:10+05:30
To format the date you have you could do some thing like:
var dateVars = "21/01/2016 10:10:10".match(/\d+/g);
var reformattedDate = dateVars[2] + '-' + dateVars[1] + '-' + dateVars[0] + 'T' + dateVars[3] + ':' + dateVars[4] + ':' + dateVars[5] + '+05:30';
new Date(reformattedDate);

First, new Date("21/01/2016 10:10:10") returns Invalid Date. Default format for Date is mm/dd/yyyy and not dd/mm/yyyy.
Second, when comparing dates, you should use date.getTime() instead.
Following is a sample code.
var endDateVal = "02/21/2016 10:10:10";
var d1 = new Date(endDateVal)
var d2 = new Date();
console.log(d1, d2)
if (+d1 > +d2) {
alert("Last end date should be minor than today");
}

You need to swap your day/month around to 01/21/2016 10:10:10.
Also, Im not sure why you are using .replace(/-/gi, "/"); as this is replacing a - with / where your date does not have any -.

Related

Trouble converting dates string to YYYY-MM-DDTHH:MM:SS-HH:MM format

I have a start date that looks like this:
var startDate = "Mon Jun 30 2014 00:00:00 GMT-0400 (EDT)";
And I am trying to get it formatted into this:
var endDate = "2014-06-30T00:00:00-04:00";
I have gotten it to semi-format correctly using the toISOString() method:
var formattedDate = new Date(startDate);
formattedDate = formattedDate.toISOString();
Which formats it into "2014-06-30T04:00:00.000Z". This is close to what I need, but I was wondering if there was built in method to format it into the '-04:00' format? Or do I need to split my string into parts and mend it back together in the right format?
Also I am working out of Google Apps Script, which is ES5, and am trying to avoid jQuery if possible.
Google Apps Script (GAS) has a built-in utility method you can leverage to format dates:
Utilities.formatDate()
Its based on Java's SimpleDateFormat class.
To format the date to meet your requirements the following should suffice:
var date = new Date("Mon Jun 30 2014 00:00:00 GMT-0400 (EDT)");
var formattedDate = Utilities.formatDate(
date,
Session.getScriptTimeZone(),
"yyyy-MM-dd'T'HH:mm:ssXXX"
);
Note: You may need to set your script's timezone from the GAS GUI menu via:
File->Project Properties->Info
I completely agree with #JordanRunning 's comment.
Still, out of curiosity I quickly put together a way to get your desired format:
// two helper functions
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
function getOffset(offset) {
if(offset<0) {
wminutes = 0 - offset;
var posneg = "-";
} else {
wminutes = offset;
var posneg = "+";
}
var hours = pad(Math.floor(wminutes/60));
var minutes = pad(wminutes % 60);
return posneg+hours+":"+minutes;
}
// the actual format function
Date.prototype.toMyFormat = function() {
var format = this.getUTCFullYear() +
'-' + pad(this.getMonth() + 1) +
'-' + pad(this.getDate()) +
'T' + pad(this.getHours()) +
':' + pad(this.getMinutes()) +
':' + pad(this.getSeconds());
timezoneOffset = getOffset(this.getTimezoneOffset());
format += timezoneOffset;
return format;
}
// usage:
console.log(new Date().toISOString());
// "2018-11-16T20:53:11.365Z"
console.log(new Date().toMyFormat());
// "2018-11-16T21:53:11-01:00"
You can just reformat the string. The format in the OP is consistent with the format specified for Date.prototype.toString in ECMAScript 2018, so you can even reformat that wiht the same function:
// Convert string in DDD MMM DD YYYY HH:mm:ss ZZ format to
// YYYY-MM-DDTHH:mm:ssZZ format
function formatDateString(s) {
var m = {Jan:'01',Feb:'02',Mar:'03',Apr:'04',May:'05',Jun:'06',
Jul:'07',Aug:'08',Sep:'09',Oct:'10',Nov:'11',Dec:'12'};
var b = s.split(' ');
return `${b[3]}-${m[b[1]]}-${b[2]}T${b[4]}${b[5].slice(-5,-2)}:${b[5].slice(-2)}`;
}
console.log(formatDateString("Mon Jun 30 2014 00:00:00 GMT-0400 (EDT)"));
// Not recommended, but it will format any date where its
// toString method is consistent with ECMAScript 2018
console.log(formatDateString(new Date().toString()));

Javascript date backward

I'm trying to compute the date of the day before using:
var da = new Date('2016-11-25');
nda = new Date(da-86400000);
It seems to work well when printed out using:
document.write(nda);
The output is:
Thu Nov 24 2016 00:00:00 GMT+0000 (WET)
which is correct, but when I do:
document.write(nda.getFullYear()+"-"+nda.getMonth()+"-"+nda.getDay());
I get a wrong output:
2016-10-4
Any suggestion?
You need to do nda.getMonth() + 1.
Months start from 0 so in order to get the right number of the month you must add 1.
Also you need to use getDate() instead of getDay(). getDay will give you the day of the week, while getDate will give you the day of the month.
The end result would be:
nda.getFullYear() + "-" + (nda.getMonth() + 1) + "-" + nda.getDate()
var da = new Date('2016-11-25');
nda = new Date(da-86400000);
document.write((nda.getFullYear())+
"-"+(nda.getMonth()+1)+
"-"+(nda.getDate()));
Date.getMonth() returns the index of the month, which is 0-indexed (So 0 is January, and 11 is December). To correct for this, you add 1.
Date.getDay() returns the day of the week, which is also 0-indexed starting from Sunday (So 4 is Thursday).
Here, you would use Date.getDate() to get the day in the current month (Which is not 0-indexed).
var da = new Date('2016-11-25'),
nda = new Date(da-86400000);
document.write(nda.getFullYear() + "-" +
(nda.getMonth() + 1) + "-" +
nda.getDate());
There is a fundamental rule wiht parsing dates: do not use the Date constructor or Date.parse (they are equivalent for parsing) to parse date strings. Use a library with a parser or parse it yourself with a simple function.
When using:
var da = new Date('2016-11-25');
the date will be treated as UTC, so if you are in a timezone that is west of Greenwich the local date will be the day before. Note the differences in the following:
console.log('Built-in parse: ' + new Date('2016-11-25').toLocaleString());
console.log('No parse : ' + new Date(2016, 10, 25).toLocaleString());
When you do:
nda.getFullYear()+"-"+nda.getMonth()+"-"+nda.getDay();
as others have said, you should use nda.getMonth() + 1, and you want getDate rather than getDay. However, since you are parsing the date as UTC then getting local values, the previous issue with UTC may mean that the date is one day previous.
To construct a date in the local time zone and avoid parsing errors, set the values directly.
To get the day before any date, simply subtract one day. Don't subtract 24 hours or you'll then get errors over daylight saving boundaries (since those days aren't exactly 24 hours long). e.g.:
/* Format a date as yyyy-mm-dd
** #param {Date} date
** #returns {string}
*/
function formatDate(date) {
return date.getFullYear() + '-' +
('0' + (date.getMonth() + 1)).slice(-2) + '-' +
('0' + date.getDate()).slice(-2);
}
var nda = new Date(2016, 10, 25);
console.log('Created date: ' + formatDate(nda));
nda.setDate(nda.getDate() - 1);
console.log('Previous day: ' + formatDate(nda));

convert javascript date format to YYYY-MM-DDTHH:MM:SS

how to convert default date in javascript to YYYY-MM-DDTHH:MM:SS format.
new Date() returns Sun Aug 07 2016 16:38:34 GMT+0000 (UTC)
and i need the current date to above format.
As new Date().toISOString() will return current UTC time, to get local time in ISO String format we have to get time from new Date() function like the following method
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('.')[0]);
You can use moment.js library to achieve this.
Try:
var moment = require('moment')
let dateNow = moment().format('YYYY-MM-DDTHH:MM:SS')
This could work :
var date = new Date();
console.log(date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
For use the date in ISO 8601 format run the command lines below on NodeJS console or on browser console:
$ node
> var today = new Date(); // or
> var today = new Date(2016, 8, 7, 14, 06, 30); // or
> var today = new Date('2016-08-07T14:06:30');
> today; // Show the date in standard USA format. Grrrr!
> today.toISOString();
For more information, consult the documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
moment is to large, you can use fecha
import fecha from 'fecha'
const uTime ="2019-10-21T18:57:33"
fecha.format(fecha.parse(uTime, "YYYY-MM-DD'T'HH:mm:ss"), 'YYYY.MM.DD HH:mm:ss')
// console.log(2019.10.21 18:57:33)
let date = new Date(Date.now());
date = now.toISOString().substr(0,now.toISOString().indexOf("."));
//2021-07-26T09:07:59
use this code:
new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('.')[0]);

Javascript convert string to date format yyyy-MM-dd

I have a string which is in the format "05-01-2016" when i run the below code in chrome i get the correct output
var fromDate = new Date(searchOpts.RunDateFrom);
fromDate.format("yyyy-MM-dd");
output = "2016/05/01"
However, when this code is execute inside my js file i get this output
Sun May 01 2016 00:00:00 GMT+0530 (India Standard Time)
How do i prevent this? I need to pass the date in this format "2016-05-01" to solr
formattedDate = fromDate.getFullYear() + "-" + (fromDate.getMonth()+1) + "-" + fromDate.getDate()
If you just need the string
var year = fromDate.getFullYear();
var month = fromDate.getMonth() < 10 ? '0'+ fromDate.getMonth()+1 : fromDate.getMonth()+1
var date = fromDate.getDate() < 10 ? '0'+ fromDate.getDate(): fromDate.getDate()

What's wrong on adding Days at this Date function?

This is my code:
var dat = new Date("24/03/2013");
dat.setDate(dat.getDate() + 7);
console.log(dat)
but it print Tue Jan 06 2015 00:00:00 GMT+0100?
The date is wrong: should be 31/03/2013 (and I'd like to print it in this format).
My browser (Chrome) prints "Invalid date", but apparently yours interprets the initializing date in mm/dd/yyyy format instead of dd/mm/yyyy. Therefore it thinks it's the 3rd day of the 24th month of 2013, which is January 3rd, 2015.
I'm not sure why it would print it as January 6th if you add 7 days to it.
The safest way is to give the numbers explicitly:
var dat = new Date( 2013, 2, 24 );
Change the format of your date to put the day after the month:
var dat = new Date("03/24/2013");
dat.setDate(dat.getDate() + 7);
console.log(dat)
For me this returns:
Sun Mar 31 2013 00:00:00 GMT+0000 (GMT Standard Time)
You should have to give the month number first. Then you'll get the correct answer
Try this code
var dat = new Date("03/24/2013");
dat.setDate(dat.getDate() + 7);
var curr_date = dat.getDate();
var curr_month = dat.getMonth() + 1; //Months are zero based
var curr_year = dat.getFullYear();
console.log(curr_date + "/" + curr_month + "/" + curr_year);
You should print out your date before you add seven. I suspect it's being set to the 3rd day of the 24th month in 2013, which equates to somewhere close to January 2015.
That's why you're getting a date well advanced from the current one. Why it's giving you the 6th of January rather than the 10th, I'm not sure, but you can probably fix it just by changing your input string to the US format of mm/dd/yyyy, or using a more explicit constructor that's not subject to misinterpretation:
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
try this!!!
var aDate = new Date(2013,3,24);
aDate.setDate(aDate.getDate() + 7);
var dateString = aDate.getDate() + "-" + aDate.getMonth() + "-" + aDate.getFullYear();
alert(dateString);

Categories

Resources