Compare string dd/mm/yyyy with currentDate format js - javascript

Hi I would to like to compare string example 15/01/2017 with newDate()
var dates = jQuery('tr.Entries').find('td.event-date > a').map(function() { //event date format is e.g 15/01/2017
return jQuery(this).text();
}).get();
var currentDate = new Date();
jQuery.each(dates, function (index, value) {
console.log(value);
//var parts = value.split('/');
//var mydate = new Date(parts[2],parts[0]-1,parts[1]);
//console.log("mydate is: "+mydate);
if(value < currentDate){
//do something
}
});

You just need to convert the current date to the same date format with which you are comparing.
var currentDate = new Date();
currentDate = ("0"+currentDate.getDate()).slice(-2) + "/" + ("0"+(currentDate.getMonth() + 1)).slice(-2) + "/" + currentDate.getFullYear();
Now your comparison with other values in dates should work fine.

Why you use less than condition inside if statement simply do this
var dates = jQuery('tr.Entries').find('td.event-date > a').map(function() { //event date format is e.g 15/01/2017
return jQuery(this).text();
}).get();
var currentDate = new Date();
jQuery.each(dates, function (index, value) {
console.log(value);
var istrue = new Date();
currentDate = ("0"+currentDate.getDate()).slice(-2) + "/" + ("0"+
(currentDate.getMonth() + 1)).slice(-2) + "/" +
currentDate.getFullYear()=="15/01/2017";
if(istrue){
//do something
}
});

Although there are vanilla-javascript and Jquery-only based solutions, if your project is big enough I'd advice you to add moment.js to your project and use it for such comparisons.
It will make your life easier.
Check it out on the moment.js website

Related

Convert 2014-11-03T00:00:00 to yyyy-mm-dd in javascript

I have tried to change this date in yyyy-mm-dd using
function convert(str) {
var date = new Date(str);
var mnth = ("0" + (date.getMonth() + 1)).slice(-2)
var day = ("0" + date.getDate()).slice(-2);
return [date.getFullYear(), mnth, day].join("-");
}
But it's giving me the error Naan in i.e 8. It's working with all other browsers.
Any one can help me in this?
Thanks
You want to go from
2014-11-03T00:00:00
to
yyyy-mm-dd
you just need
function convert(str) {
return str.split("T")[0];
}
To create a date from one with a T and dashes, try
function convert(str) {
var parts = str.split("T");
var dParts = parts[0].split("-");
var tParts = parts[1].split(":");
return new Date(dParts[0],dParts[1],dParts[2],tParts[0],tParts[1],tParts[2]);
}
var d = convert("2014-11-03T00:00:00");
alert(d);

Javascript - compare date/time now against yyyy/mm/dd hh:mm:ss

I have a date/time in an input (#myinput) using the following format:
yyyy/mm/dd hh:mm:ss
I need to compare this to todays date, so something like this...
var currentdate = new Date();
if(currentdate < $("#myinput").val()) {
alert("HELLO WORLD");
return false;
}
Any ideas?
I am using moment.js (http://momentjs.com/) for this kind of work.
Would look something like this:
var input = moment($("#myinput").val(), "YYYY/MM/DD HH:mm:ss");
if(input.diff(moment())>0){
...
If i had to use javascript only, i would use a regular expression to parse the date:
var dateString = "2012/12/05 12:00:01";
var regexp = /([0-9]{4})\/([0-9]{2})\/([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/;
var result = regexp.exec(dateString);
var date = new Date();
date.setYear(result[1]);
date.setMonth(result[2]-1);
date.setDate(result[3]);
date.setHours(result[4]);
date.setMinutes(result[5]);
date.setSeconds(result[6]);
if(new Date()<date){
...
You can use the Date.Parse method (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/parse) to compare the date inside your input against the current date or other dates in any kind of correct date format.
Ex:
var testDate = $('#myinput').val();
var d = new Date;
if (Date.parse(d)<Date.parse(testDate)) {
}
else{
}
Here is a fiddle: http://jsfiddle.net/uLybp/3/
use this function
//get full data now
function dateNow(){
var now = new Date(Date.now());
var dd=now.getDay() + "-" + (now.getMonth()+1) + "-" + now.getFullYear()+" ";
dd += now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
return dd;
}
example
var d=dateNow();
console.log(d); // 5-2-2021 1:35:24

Date validation with JavaScript

I have a date string in this format - "DD-MM-YYYY"
this validates that successfully:
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-\d{4}/ ;
if(!startDate.match(dateFormat)){
alert("'Start Date' must be in format: DD-MM-YYYY");
return false;
I need to check that the inserted date is after today's date(or today's date).
how can i do that with JavaScript?
I've tried this:
http://www.redips.net/javascript/date-validation/
with the separator, didn't work. suggestions?
First, this is your current date in javascript:
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1; // Zero indexed
All you need to do, from here, is to compare this with your start date!
Best regards!
check this out maybe it helps to understand the date object.
Check out date.js, specifically...
http://code.google.com/p/datejs/wiki/APIDocumentation#compare
Compares the first date to the second date and returns an number
indication of their relative values. -1 = this is < date. 0 =
values are equal. 1 = this is > date.
The isAfter() and the isBefore() methods might be useful for your problem :)
Download the library here:
http://code.google.com/p/datejs/downloads/detail?name=date.js&can=2&q=
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
You could do this with moment.js pretty easily.
var input = moment(startDate, "DD-MM-YYYY");
if (input < moment()) {
// before today
} else {
// after today
}
We're also adding date validation pretty soon. See more info about validation here: https://github.com/timrwood/moment/pull/306
Something like this should work. Could use some cleanup, but hopefully gets the point across.
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-(\d{4})/;
var dateMatch = startDate.exec(dateFormat);
var today = new Date();
today.setHours(0); today.setMinutes(0); today.setSeconds(0); today.setMilliseconds(0);
if ((new Date(dateMatch[3], dateMatch[2] - 1, dateMatch[1])).getTime() >= today.getTime()) {
// Date is after or on today
}
You should check each date getTime() method and compare it. It's plain and simple, you don't need additional frameworks.
Here is an example that parses the dates from the strings, and then compares them:
var todayDate = "10-05-2012";​ // A sample date
var compareDate1 = "10-05-2012";
var compareDate2 = "03-05-2012";
var compareDate3 = "10-07-2012";
compareDates(todayDate, compareDate1);
compareDates(todayDate, compareDate2);
compareDates(todayDate, compareDate3);
function compareDates(date1String, date2String) {
var date1 = parseDate(date1String);
var date2 = parseDate(date2String);
if(date1.getTime() > date2.getTime()) {
alert("First date(" + date1String + ") is older than second date(" + date2String + ").");
} else if(date1.getTime() < date2.getTime()) {
alert("First date(" + date1String + ") is younger than second date(" + date2String + ").");
} else {
alert("The dates are the same day");
}
}
function parseDate(stringDateParam) {
var parsedDay = parseInt(stringDateParam.substring(0,2));
var parsedMonth = parseInt(stringDateParam.substring(3,5))-1;
var parsedYear = parseInt(stringDateParam.substring(6,10));
var parsedDate = new Date(parsedYear, parsedMonth, parsedDay, 0 , 0, 0, 0);
return parsedDate;
}
​
// Output:
//
// First check: The dates are the same day
// Second check: First date(10-05-2012) is older than second date(03-05-2012).
// Third check: First date(10-05-2012) is younger than second date(10-07-2012).
You probably already have a function that parses string to date object, and you should implement a check similar to the one in function compareDates based on getTime() function.
If you have further questions, leave a comment. Good Luck!
JSFiddle working example: click here
Thank you all!
this did the trick:
var today = new Date();
var Tday = today.getDate();
var Tmonth = today.getMonth()+1; // Zero indexed
var Tyear = today.getFullYear();
var aoDate;
var separator= '-';
aoDate = startDate.split(separator);
var month = aoDate[1] - 0;
var day = aoDate[0] - 0;
var year = aoDate[2] - 0;
if(year < Tyear){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month < Tmonth)){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month == Tmonth) && (day < Tday)){
alert("'Start Date' must be today or after today!");
return false;
}
Like most I was surprised a what js accepts as the constituent parts of a date. There may be holes in the code below which I would be glad to hear about but this seems to work for me. This assumes a DD/MM/YYYY HH:mm input format.
function strToDate(dtStr) {
if (!dtStr) return null
let dateParts = dtStr.split("/");
let timeParts = dateParts[2].split(" ")[1].split(":");
dateParts[2] = dateParts[2].split(" ")[0];
// month is 0-based, that's why we need dataParts[1] - 1
return dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0], timeParts[0], timeParts[1]);
}
// start of validation
var end_time = $('#tbDepartDtTm').val();
end_actual_time = strToDate(end_time);
// convert the date object back to a string in the required format
var dtString = ("0" + end_actual_time.getDate()).slice(-2) + "/" + ("0" + (end_actual_time.getMonth() + 1)).slice(-2) + "/" + end_actual_time.getFullYear() + " " + ("0" + end_actual_time.getHours()).slice(-2) + ":" + ("0" + end_actual_time.getMinutes()).slice(-2);
if (dtString != end_time) {
// if the string isn't the same as entered, it must be invalid. msg is a span element.
msg.textContent = "Depart date is not a valid date.";
return "Error";
}

How to format dates in javascript

I pick this date from a textbox and i would like to format to this format: yyyy-MM-dd
So from dd/MM/yyyy to yyyy-MM-dd
var startDate = document.getElementById('ctl00_PlaceHolderMain_ctl00_Date').value;
var s = new Date(startDate);
alert(startDate); //which prints out 7/03/2012
//when i use the below to try and format it to : yyyy-MM-dd which is what i want
var scurr_date = s.getDate();
var scurr_month = s.getMonth();
scurr_month++;
var scurr_year = s.getFullYear();
For some reason i get:
var fstartdate = scurr_year + "-" + scurr_month + "-" + scurr_date;
//Output:2012-7-3
instead of : 2012-3-7
also fi i pick a date like 31/12/2011
i get : 2013-7-12
Any ideas what to do.I kind of notice if i use US like 03/07/2012 it kind os works ok.
Thank in advance
You said you want to convert from "dd/MM/yyyy to yyyy-MM-dd". JavaScript's Date constructor will always take the first two digits as a month.
Some regex might help you here:
function fix_date (str) {
var re = /(\d{1,2})\/(\d{1,2})\/(\d{4})/;
str = str.replace(re, function (p1, p2, p3, p4) {
return p4 + '/' + p3 + '/' + p2;
});
return str;
}
var start_date = '7/03/2012';
var new_date = fix_date(start_date);
console.log(new_date); // 2012/03/7​
http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
and this
http://www.elated.com/articles/working-with-dates/
Basically, you have 3 methods and you have to combine the strings for yourself:
getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year
<script type="text/javascript">
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //months are zero based
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
</script>
check this answer link

Compare 2 dates in format DD/MM/YYYY with javascript/jquery

Suppose I receive two dates from the datepicker plugin in format DD/MM/YYYY
var date1 = '25/02/1985'; /*february 25th*/
var date2 = '26/02/1985'; /*february 26th*/
/*this dates are results form datepicker*/
if(process(date2) > process(date1)){
alert(date2 + 'is later than ' + date1);
}
What should this function look like?
function process(date){
var date;
// Do something
return date;
}
Split on the "/" and use the Date constructor.
function process(date){
var parts = date.split("/");
return new Date(parts[2], parts[1] - 1, parts[0]);
}
It could be more easier:
var date1 = '25/02/1985'; /*february 25th*/
var date2 = '26/02/1985'; /*february 26th*/
if ($.datepicker.parseDate('dd/mm/yy', date2) > $.datepicker.parseDate('dd/mm/yy', date1)) {
alert(date2 + 'is later than ' + date1);
}
For more details check this out. Thanks.
function process(date){
var parts = date.split("/");
var date = new Date(parts[1] + "/" + parts[0] + "/" + parts[2]);
return date.getTime();
}

Categories