This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
I have a date-picker on my web application that produces the following output 25-04-2018 16:50:
It is: day-month-year hour:minute.
The idea is that I'll have two input-text, and the first date has to be before the second date. Otherwise, swap the dates.
I want to compare two dates in this format, so I try to create a Date object:
<input onchange="date()" type="text" readonly id="datetimepicker_1"/>
<input onchange="date()" type="text" readonly id="datetimepicker_2"/>
<script>
function date() {
var start = document.getElementById("datetimepicker_1");
var end = document.getElementById("datetimepicker_2");
if (start.value.trim() && end.value.trim()) {
var dateStart = new Date(start.value);
var dateEnd = new Date(end.value);
if (dateStart > dateEnd){
document.getElementById("datetimepicker_1").value = end.value;
document.getElementById("datetimepicker_2").value = start.value;
}
}
</script>
But I have the following error: Invalid Date. How I can compare these dates?
It looks like JavaScript isn't tolerating the format of your date.
You have the date in format of "Day-Month-Year Hour-Minute" Or DD-MM-YYYY
I was able to get the following code to work in two scenarios; having the date in the format : "Year-Month-Day Hour-Minute" or "Month-Day-Year Hour Minute"
This code is very poorly written but I think it illustrates the idea.
function DatePicker()
{
var datestart = new Date("2018-04-25 16:50"); //or 04-25-2018 16:50
console.log(datestart);
var datestart2 = new Date("2018-04-25 16:55"); //or 04-25-2018 16:50
console.log(datestart2);
if (datestart < datestart2)
{
console.log("success");
} else {
console.log("failed");
}
}
DatePicker();
I recognize that different countries in the world use different date formats. So to solve your issue I would recommend using "Moment.js" so you are able to format the date to your liking or needs as laid out in the Stack Overflow question and answer linked below.
DD/MM/YYYY Date format in Moment.js
Related
This question already has answers here:
What are valid Date Time Strings in JavaScript?
(2 answers)
Closed 1 year ago.
I have two dates .
var dateOne = "24/04/1995"
var dateTwo = "24/04/1998"
How can i check if one date is bigger than the other?
I tried this :
function myFunction() {
var d1 = Date.parse(dateOne);
var d2 = Date.parse(dateTwo);
if (d1 < d2) {
alert ("Error! Date did not Match");
}
}
but its not working =(
there is a method for this dd/mm/yyyy format?
Relying on the docs around Date
JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.
You can simply cast to a Number and compare:
const isDateOneBigger = +dateOne > +dateTwo;
However in your case your Dates are invalid. You can check this by logging out d1 which will result in NaN. If you take a look at How to convert dd/mm/yyyy string into JavaScript Date object? you'll see how you can convert your strings into correct dates.
use the getTime() as so
function myFunction() {
var d1 = new Date(dateOne);
var d2 = new Date(dateTwo);
if (d1.getTime() < d2.getTime()) {
alert ("Error! Date did not Match");
}
}
the getTime() method convert the date into milliseconds
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 4 years ago.
I'm using mydatepicker in my Angular application. When user clicks a specific date I'm getting the selected date. But I want to have a date format like this.
20180320
or
2018-03-20
So what I did was to convert as follows.
onDateChange(event) {
this.selectDate = event.jsdate.toISOString().slice(0,10)
}
This helps me to get my format. But it shows a day before. That means , if a user selects 2018-03-20 from calendar my selectDate = 2018-03-19
I can do that using moment , but for this project I'm not using for some reasons.Could someone help me to correct this?
Try this to account for timezone
onDateChange(event){
var localDate = new Date(event.jsdate.getTime() - event.jsdate.getTimezoneOffset() * 60000);
this.selectDate = localDate.toISOString().slice(0,10);
}
toISOString is always in UTC+0 time. If you console.log it, you should see a Z on the end. That means GMT.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
Just try this with prototype function
Date.prototype.getDDMMYYYY = function () {
var date = JSON.stringify(this.getDate()).length == 1 ? ("0" + this.getDate()) : this.getDate();
var month = JSON.stringify(this.getMonth()).length == 1 ? ("0" + this.getMonth()) : this.getMonth();
var year = this.getFullYear();
return year+"-"+month+"-"+date;
}
and Just replace this code
onDateChange(event){
this.selectDate = event.jsdate.getDDMMYYYY()
}
This question already has answers here:
How to validate a date?
(11 answers)
Closed 6 years ago.
How to validate a date? I mean not the format, but the logic.
For example: Feb 30th is not a valid date.
var date = new Date("2015-02-29T13:02:49.073Z"); // 2015 Feb 29th does not exist
console.log(date.toISOString());
Returns 2015-03-01T13:02:49.073Z (March 1st).
But I want a information that this date (input) is not valid.
Edit:
Tested in Chrome. Firefox returns "invalid date". But not on parsing.
Only when the date is used (e.g. toISOString()) an exception is thrown.
try
{
var date = new Date("2015-02-29T13:02:49.073Z");
console.log(date.toISOString());
}
catch(e)
{
console.log("error: " + e.message);
}
Firefox:
invalid date
Chrome:
(nothing, just switched to the next date.)
Summary: It is browser-dependent. So, not recommended to use.
jsfiddle example
I use this function to check whether a date is valid or not:
function isValidDate(year, month, day) {
month = month - 1;
var d = new Date(year, month, day);
if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) {
return true;
}
return false;
}
The easiest thing I can think of, is to convert the parsed date to ISO string and compare it to the original input:
var input = "2015-02-29T13:02:49.073Z"
var date = new Date(input);
var isValid = (input === date.toISOString());
I wrote small function for you:
function check_date(str){
try{
return str == new Date(str).toISOString()
}catch(e){
return false;
}
}
Try this
console.log(check_date('2015-02-01T13:02:49.073Z'));
console.log(check_date('2015-02-35T13:02:49.073Z'));
console.log(check_date('2015-02-29T13:02:49.073Z'));
https://jsfiddle.net/8o040ctr/
I've found that behavior rather amusing. I used to just convert the input to a date (as you've done), then update the text in the textbox to show the date as interpreted by JavaScript so the user would see the resulting (valid) date.
Luckily, we can do much better now. Moment.js is a fantastic library for dealing with date/time values in JavaScript. It's sure made life a lot easier for me!
http://momentjs.com/
If you pass a string that starts with 'YYYY-MM' format, like you have in the question, you could use this function:
function makeDate(s) {
var date = new Date(s);
if (date.toISOString(date).substr(0,7) != s.substr(0,7)) throw "Invalid date";
return date;
}
dt = makeDate('2015-02-29T13:02:49.073Z');
This makeDate function would replace the plain new Date(...) call, but will also throw an error in Chrome when it is passed an invalid date string.
Dates in browsers are always very tricky, I suggest you to use a js lib like moment: http://momentjs.com/
then you can use .isValid() method for ex.:
moment('03:55', 'HH:mm').isValid();
moment('2012-05-25', 'YYYY-MM-DD').isValid();
moment('2015-02-29T13:02:49.073Z', "YYYY-MM-DDTHH:mm:ss", true).isValid();
This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 9 years ago.
I want to get day from date. Suppose my date is 03-08-2013 it is in d-mm-yyyy format so I just want to get dand that is 03 from above date so I try this code but it does not work
Note
I want to do it without including any js
var date = '08-03-2013';
var d = new Date(date);
alert(d.getDate());
// 2nd way
alert(date.getDate());
it alert NaN. What is missing in this code?
here is jsfiddel Link Jsfiddle Link
UPDATE
Date parsing in JS (and many languages, for that matter) is problematic because when the input is a date string, it's fairly ambiguous what piece of data is what. For example, using your date (August 3, 2013) it could be represented as
03-08-2013 (dd-mm-yyyy)
08-03-2013 (mm-dd-yyyy)
However, given just the date string, there's no way to tell if the date is actually August 3, 2013 or March 8, 2013.
You should pass your date values independently to guarantee the date is correctly parsed:
var
str = '08-03-2013',
parts = str.split('-'),
year = parseInt(parts[2], 10),
month = parseInt(parts[1], 10) - 1, // NB: month is zero-based!
day = parseInt(parts[0], 10),
date = new Date(year, month, day);
alert(date.getDate()); // yields 3
MDN documentation for Date
You can't know the regional settings of your visitors.
If you know the format of the string is always d-mm-yyyy then just parse the value yourself:
function GetDay(rawValue) {
var parts = rawValue.split("-");
if (parts.length === 3) {
var day = parseInt(parts[0], 10);
if (!isNaN(day))
return day;
}
alert("invalid date format");
return null;
}
Live test case.
Use moment.js. It's parsing ability is much more flexible than the Date class.
var m = moment('03-08-2013','DD-MM-YYYY');
var dayOfMonth = m.date();
Use this it that which you want..
var date = '08-03-2013';
date=date.replace(/([0-9]{2})\-([0-9]{2})\-([0-9]{4})/g, '$3-$2-$1');
var d = new Date(date);
alert(d.getDate());
Thanks
I have one xml file which is retrieved using jquery in sharepoint. One of the row of the xml is like below.
<z:row ows_Title='Have dinner party with Host' ows_Due_x0020_Date='2012-05-10 00:00:00' ows_MetaInfo='1;#' ows__ModerationStatus='0' ows__Level='1' ows_ID='1' ows_UniqueId='1;#{2A8F277A-C95B-420C-89A9-3B979F95C8F4}' ows_owshiddenversion='3' ows_FSObjType='1;#0' ows_Created='2012-10-25 03:19:35' ows_PermMask='0x7fffffffffffffff' ows_Modified='2012-10-29 00:56:09' ows_FileRef='1;#personal/Inclusions/Lists/Events/1_.000' />
Now i want to retireve the "Due Date" column and compare with the today's date. For retrieving date there is no issue. But how to compare the both dates? For comparing the date with today I used like this.
var k = new Date();
var year = k.getYear();
var month = k.getMonth();
var day = k.getDate();
var fulldate = year+"-"+month+"-"+day
But it is displaying only with date. In xml we are getting time also. I dont want to compare with time. I want to compare with only dates. How to achieve it? I want to put that whole process in the following function.
$(xData.responseXML).find("z\\:row").each(function() {
//here i want to compare that date column with present date
});
Finally i want, the date coming in the xml is less than the today's date or not?
Something like this:
function isPastDate( date ) {
return (new Date( date )).getTime() < (new Date()).getTime();
}
Highly recommend Date.js library for all the comparison and formatting methods that can make a lot of date work greatly simplified
http://www.datejs.com/
finally the required comparison like below.
function compareDates(passdate)
{
var splitdate = passdate.split(" ");
var splitdate1 = splitdate[0].split("-");
var newdate = splitdate1[1]+"-"+ splitdate1[2]+"-"+splitdate1[0];
return ((Date.parse(newdate)) < (new Date()).getTime());
}