Date Comparison Using Javascript [duplicate] - javascript

This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 8 years ago.
I have two date strings in DDMMYYYY format. say startdate="18/02/2013" and enddate ="26/02/2013".
How can I compare these dates. I want enddate to be greater than or equal to startdate
Thanks for Your Time.

I'm a fan of moment.js and consider it a core part of my toolkit whenever I have to deal with dates and times - especially when any form of parsing or formatting is involved.
You're free to do the parsing by hand and invoke the appropriate Date constructor manually, but consider the following which I consider simple and intuitive.
var startDate = moment.parse("18/02/2013", "DD/MM/YYYY");
var endDate = moment.parse("26/02/2013", "DD/MM/YYYY");
if (endDate.isAfter(startDate)) {
// was after ..
}

Does this solution suits your needs (demo : http://jsfiddle.net/wared/MdA3B/)?
var startdate = '18/02/2013';
var d1 = startdate.split('/');
d1 = new Date(d1.pop(), d1.pop() - 1, d1.pop());
var enddate = '26/02/2013';
var d2 = enddate.split('/');
d2 = new Date(d2.pop(), d2.pop() - 1, d2.pop());
if (d2 >= d1) {
// do something
}
Keep in mind that months begin with 0. MDN doc :
month : Integer value representing the month, beginning with 0 for January to 11 for December.

var d1 = Date.parse("18/02/2013");
var d2 = Date.parse("26/02/2013");
if (d1 > d2) {
alert ("do something");
}

Related

Check if date is bigger then other date (dd/mm/yyyy) [duplicate]

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

Comparing datetime to the current date javascript [duplicate]

This question already has answers here:
How to know date is today?
(3 answers)
Closed 2 years ago.
I have an object that contains a property of date with a value of 2020-09-02T00:00:00.000Z. I want this value to be compared if it is within the current date or not, meaning if it is within 2020-09-01 00:00:00.00 to 2020-09-01 11:59:59.99. How will I be able to achieve this? This is my initial line of codes. Hope you can help me. Cheers!
for(let a = 0, c = arr3.length; a < c; a++){
let olddate = arr3[a].scheduled_time_start.valueOf();
}
You can compare native Date objects with comparison (<, <=, >, >=) operators.
const isDateInbetween = (date, startDate, endDate) =>
date > startDate && date < endDate;
const pastDate = new Date('2020-09-01T00:00:00.000Z');
const futureDate = new Date('2020-09-01T11:59:59.999Z');
const currDate = new Date('2020-09-02T00:00:00.000Z');
console.log(isDateInbetween(currDate, pastDate, futureDate)); // false

Comparing the current date with a date received from an api response [duplicate]

This question already has answers here:
How to calculate date difference in JavaScript? [duplicate]
(24 answers)
Closed 4 years ago.
I want to compare the date I receive from an API to the current date and if it exceeds 14 days. The date I receive is in this format.
"date": "2018-08-07T14:17:24+02:00"
You can use the library date-fns to calculate this too. It has a smaller bundle size than Moment.
function exceedsDays(date, numberOfDays) {
var today = dateFns.startOfToday();
var diff = dateFns.differenceInDays(today, dateFns.parse(date));
return diff > numberOfDays;
}
var date = "2018-08-07T14:17:24+02:00";
var result = exceedsDays(date, 14);
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>
let dateFrom = new Date("2018-08-07T14:17:24+02:00").getTime();
let today = new Date().getTime();
let days14 = 1000 * 60 * 60 * 24 * 14;
if(today - dateFrom > days14){ }
If you go with momentjs you can do something like that. This will return you a boolean. You can reuse later this function to maybe check if more than 30 days etc. Just need to change the second argument. The first one is your date you want to check. By default moment() return now, this is the reason we don't need to create a date for now.
const oldDate = '2018-08-07T14:17:24+02:00';
function exceedNumOfDays(date, numOfDays) {
return moment().diff(new Date(date), 'days') > numOfDays;
}
exceedNumOfDays(oldDate, 14)
I put the code on codesandbox, you can see the console at the bottom left. https://codesandbox.io/s/oo967v83xq

Get day from Date in JavaScript [duplicate]

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

Javascript get date in format [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
I want to get today's date in the format of mm-dd-yyyy
I am using var currentDate = new Date();
document.write(currentDate);
I can't figure out how to format it.
I saw the examples var currentTime = new Date(YY, mm, dd); and currentTime.format("mm/dd/YY");
Both of which don't work
I finally got a properly formatted date using
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0!`
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
var today = mm+'/'+dd+'/'+yyyy;
document.write(today);'`
This seems very complex for such a simple task.
Is there a better way to get today's date in dd/mm/yyyy?
Unfortunately there is no better way, but instead of reinventing the wheel, you could use a library to deal with parsing and formatting dates: Datejs
<plug class="shameless">
Or, if you find format specifiers ugly and hard to decipher, here's a concise formatting implementation that allows you to use human-readable format specifiers (namely, the Date instance getters themselves):
date.format("{Month:2}-{Date:2}-{FullYear}"); // mm-dd-yyyy
</plug>
var today = new Date();
var strDate = 'Y-m-d'
.replace('Y', today.getFullYear())
.replace('m', today.getMonth()+1)
.replace('d', today.getDate());
Simple answer is no. Thats the only way to do it that I know of.
You can probably wrap into a function that you can reuse many times.
date.js is what you need. For example, snippet below is to convert a date to string as Java style
new Date().toString('M/d/yyyy')
function dateNow(splinter){
var set = new Date();
var getDate = set.getDate().toString();
if (getDate.length == 1){ //example if 1 change to 01
getDate = "0"+getDate;
}
var getMonth = (set.getMonth()+1).toString();
if (getMonth.length == 1){
getMonth = "0"+getMonth;
}
var getYear = set.getFullYear().toString();
var dateNow = getMonth +splinter+ getDate +splinter+ getYear; //today
return dateNow;
}
format this function is mm dd yyyy
and the dividing you can choice and replace if you want... for example
dateNow("/") you will get 12/12/2014
There is nothing built in, but consider using this if you are already using jQuery (and if not, then you should consider that as well!)
http://plugins.jquery.com/project/jquery-dateFormat
(new Date()).format("MM-dd-yyyy")
N.B. month is "MM" not "mm"
function appendZeros(value,digits){
var c= 1;
initValue = value;
for(i=0;i<digits-1;i++){
c = c*10;
if( initValue < c ){
value = '0' + value;
}
}
return value;
}

Categories