Compare one date with today using DD-MM-YYYY format - javascript

I want to compare a date (mydate) with today. I tried
new Date(mydate) < new Date();
which works in all cases apart from the case my date equals today. In that case the above returns true since it compares the time included. However, I want to compare only the date, not the time.
I tried moment.js as well:
moment(mydate).format('DD-MM-YYYY')<moment().format('DD-MM-YYYY')
however, not even this one did work. What do I have to write?

You can use moment function isSame and provide the second argument as the granularity level you want for your comparison. The granularity levels can be strings like, 'year', 'month', 'day'
moment('2010-01-01').isSame('2010-02-01', 'day');
You can also look into similar functions documented over there which might help you better with your requirement.
Is Before
Is Same
Is After
Is Same or Before
Is Same or After
Is Between
All of these supports different granularity levels.
As a sidenote, to create a date in your supplied format do:
moment("25-12-1995", "DD-MM-YYYY");

You can simply do following using moment js
$(document).ready(function() {
$('.compare').click(function(e) {
var date = $('#date').val();
var now = moment().format('YYYY-MM-DD');
var then = moment(date).format('YYYY-MM-DD');
if (now > then) {
$('.result').text('Date is past');
} else if(now == then) {
$('.result').text('Date is today');
} else {
$('.result').text('Date is future');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<input type="text" name="date" id="date" value="2014-12-18" placeholder="yyyy-mm-dd">
<button class="compare">Compare date to current date</button>
<br>
<div class="result"></div>

Related

moment.js change format based on difference

I want to follow the same structure as content posting websites where new posts follow something like:
(seconds/minutes/hours ago), (yesterday), (days ago), (MMM Do YY).
How would I rearrange the JS to follow this format and go to (MMM Do YY) after say, 3 days?
// iterates over every element with the .js-time-ago css class
$('.date').each(function() {
var $this = $(this),
textDate = $this.data('date'), // gets the date from the date attribute
postedDate = moment(textDate, ['DDMMMMY', 'MMMMDDY']).format(), // formats the date in a formate that will continue to be supported by Moment JS
today = moment().format(), // gets today's date
timeSince = moment(today, 'YYYY-MM-DD').diff(moment(postedDate, 'YYYY-MM-DD'), 'days'); // sets up the dates to be compared so that we can get a number for if statement below
if (timeSince >= 0) $this.text(moment(postedDate).fromNow());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<div class="date" data-date="01 April 2018"></div>
<div class="date " data-date="26 May 2018"></div>
<div class="date" data-date="27 May 2018"></div>
We can acheive what you want by doing two things to your code first passing ing 'day' into the moment().diff() function to get the difference in days then checking that value is smaller than 3 using a ternary statement very similar to an if.
I've cleaned up the code abit to show the 5 steps i'm taking
Storing the time now outside the loop
get the date from the attribute
get the difference in days
format the date based on if its less than 3 days
appending that value to the element
function formatDate() {
const NOW = new Date();
$('.date').each(function() {
const DATE = new Date($(this).data('date'));
const DIFF = moment(NOW).diff(DATE, 'day');
const FORMAT = DIFF < 3 ?
moment(DATE).fromNow() :
moment(DATE).format('MMM Do YY');
$(this).text(FORMAT);
});
}
formatDate()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<div class="date" data-date="01 April 2018"></div>
<div class="date " data-date="26 May 2018"></div>
<div class="date" data-date="27 May 2018"></div>
You're actually really close - you just need to implement the conditional logic based on timeSince being within the range you want, in your example 3 days.
If you simply switch your if statement with a ternary (or even an IF-ELSE) that checks to see if the timeSince value is less than or equal to 3, you can achieve the desired result. Here's the ternary statement to use in place of your current if one:
(timeSince <= 3) ? $this.text(moment(postedDate).fromNow()) : $this.text(moment(postedDate).format('MMM Do YY'));
The ternary/conditional statement first takes a condition to evaluate - in your case, whether or not timeSince is less than or equal to 3 days ago. If the condition is true, the first expression is executed - in this case, formatting the value from your .date selector using Moment's x ago format. If the condition is false, meaning more than 3 days ago in this example, it uses Moment to format the text using the MMM Do YY format.
Complete CodePen example here: https://codepen.io/anon/pen/zjgbmp
For an example of how a ternary helps keeps your code concise, here's the same solution using IF-ELSE:
if (timeSince <= 3) {
$this.text(moment(postedDate).fromNow());
}
else {
$this.text(moment(postedDate).format('MMM Do YY'));
}

momentjs for only time value

I use momentjs to work with date and time
let dateAndTime = moment(component.props.data.value, moment.ISO_8601);
let date = '',
time = '';
if (dateAndTime) {
if (moment(dateAndTime, 'YYYY-MM-DD', true).isValid()) {
date = moment(dateAndTime).format('YYYY-MM-DD');
}
if (moment(dateAndTime, 'HH:mm', true).isValid()) {
time = moment(dateAndTime).format('HH:mm');
}
}
this code works just fine if component.props.data.value contains date and time like 2018-05-22 14:45 or if it contains only date like 2018-05-22. The problem is sometimes component.props.data.value contains only time like 14:45, so moment(component.props.data.value, moment.ISO_8601) doesn't create moment object and code below doesn't execute. Is there any way to handle case only for time?
You can use moment(String, String[]), as the docs says:
If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.
This is the same as String + Format, only it will try to match the input to multiple formats.
Your first line of code could be like the following:
let dateAndTime = moment(component.props.data.value, [moment.ISO_8601, 'HH:mm']);

Date input type validation in javascript?

I can't quite figure out how to validate a date input type in javascript. I tried looking on the internet but I just couldnt find anything.
I have one field that ask the user to input its birthday. I want to validate it in javascript with the certain limits on days months and, especially years. For example if the user input more than 2016(or the current year) it would give an error.
I can't quite figure out how to "extract" the date input type and control every elements of it (day, month, year).
Here part of my html
<form method="POST" action="request.jsp" onsubmit="return validate()">
Date of birth: <input type="date" id="bday" name="bday" value="">
</form>
Javascript:
var birthday = document.getElementById('bday').value;
This is all i've got.. please help?
TLDR
You have to parse the string as a date (JavaScript provides the Date API for this very use case).
Full answer
You're on the right track. Here's a JSBin example I did. Try opening the console and changing the date, and you'll see it logged.
$('#birthday').on('change', function() {
console.log(new Date(this.value));
});
(I'm using jQuery in the above example just for convenience sake, but you can use whatever you want.)
The problem you have here is that the date is logged as a string. You can use the JavaScript Date object to parse the string.
Based on whatever validation you want to do, you can use various date object methods (like getFullYear, for example) and match those against the input.
I'll leave the full implementation up to you, but the inside of the change handler might look like:
var date = new Date(this.value);
if(date.getFullYear() > 2016) {
// do something (like show a message, for example)
}
If you are able to get the value of the input element with:
var birthday = document.getElementById('bday').value;
Then birthday will be available to you as a string (all input values are always returned to JavaScript as strings). From there, you'd need to convert that string to a date with:
var dob = Date.parse(birthday);
Then, once you've got the entire date, you can extract the pieces of it with the various JavaScript Date/Time methods:
var month = dob.getMonth(); // months start counting from zero!
var day = dob.getDate();
var year = dob.getFullYear(); // getYear() provides 3 digit year!
Here's a working example:
var birthday = null, btn = null, output = null;
// Wait until the document is ready for interaction:
window.addEventListener("DOMContentLoaded", function(){
// Get references to DOM elements needed:
birthday = document.getElementById('bDate');
btn = document.getElementById('btnGetDate');
output = document.getElementById('result');
// Set up an event callback for when the button gets clicked:
btn.addEventListener("click", function(){
// Create a new Date that converts the input date
var dob =new Date(birthday.value);
alert(dob);
// Extract pieces of the date:
var month = dob.getMonth(); // months start counting from zero!
var day = dob.getDate();
var year = dob.getFullYear();
// Now that you have the pieces of the date, you can validate as you wish:
// e.g. if(year > 2016) { . . . }
// Write out date:
output.innerHTML = ++month + "/" + ++day + "/" + year;
});
});
<input type="date" id="bDate">
<input type="button" id="btnGetDate" value="Get Date">
<p id="result"></p>
NOTE: Keep in mind that Daylight Savings Time will have an effect on
the result depending on what time of day it is. See:
How to check if the DST (Daylight Saving Time) is in effect and if it is what's the offset?
for more info. on that.
Input type date is not supported in all browsers, so you should detect that and replace the input with a suitable alternative that includes the format that is required.
Where supported, the input will return an ISO 8601 format date string without a time zone. According to ISO 8601, this should be treated as local, but TC39 in their wisdom decided that it should be treated as UTC, so that is what Date.parse (and the Date constructor) will do in most cases. In some it will be treated as local and in IE 8 as invalid. So for systems with a timezone that is west of Greenwich, Date.parse('2016-03-20') will return a Date object that, when displayed as a local date, will be '2016-03-19', i.e. one day early.
So you should manually parse the date string, validate the date using one of the many answers here, then check whether the year, month and day are within your constraints.
if you're simply trying to validate whether or not a string is a valid date, you can just check that it creates a valid date object.
function isValidDate(d){
return !isNaN((new Date(d)).getTime());
}
https://jsfiddle.net/46cztok6/
so your validate() function would look like this.
function validate(){
var birthday = document.getElementById('bday').value;
if(!isValidDate(birthday)){
alert("you did not enter a valid birthday");
return false;
}
}
Here is a bin so you can have an idea how to start validating this type of field: https://jsbin.com/lifacaxonu/edit?html,js,console,output
$('#birthday').on('change', function() {
var val = this.value.split('-');
if (val[0] > new Date().getFullYear()) {
console.log('invalid')
} else {
console.log('ok')
}
});
After looking out for 3 hours, i wrote this and achieved dd/mm/yyyy date input using plain Javascript.
<div class="container">
<div class="datetime-container">
<input type="text" placeholder="write your date" id="datetime" onblur="validateDate()">
<p id="error"></p><br>
<input type="tel" maxlength="10" placeholder="dd/mm/yyyy"
oninput="this.value = DDMMYYYY(this.value, event)" />
</div>
</div>
<script>
function DDMMYYYY(value, event) {
let newValue = value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1');
const dayOrMonth = (index) => index % 2 === 1 && index < 4;
// on delete key.
if (!event.data) {
return value;
}
let currentYear = new Date().getFullYear();
console.log(newValue.slice(2,4));
if(newValue.length>=2 && newValue.slice(0,2)>31){
tempValue = newValue;
newValue = tempValue.replace(tempValue.slice(0,2),31);
document.getElementById("error").style.display = "initial";
document.getElementById("error").innerHTML = "Invalid day!";
}else if(newValue.length>=4 &&newValue.slice(2,4)>12){
document.getElementById("error").style.display = "initial";
document.getElementById("error").innerHTML = "Invalid month!";
tempValue = newValue;
newValue = tempValue.replace(tempValue.slice(2,4),12);
}else if(newValue.length==8 && newValue.slice(4)>currentYear){
tempValue = newValue;
newValue = tempValue.replace(tempValue.slice(4),currentYear);
document.getElementById("error").style.display = "initial";
document.getElementById("error").innerHTML = "Invalid year!";
}
else{
document.getElementById("error").style.display="none";
}
return newValue.split('').map((v, i) => dayOrMonth(i) ? v + '/' : v).join('');;
}
</script>

Difference (in days) between two days in yyyy-mm-dd format?

Sorry if this has been asked before, but I haven't been able to find anything. Here's essentially what I'm trying to do:
new Date(response.departureDate).getTime() - new Date(response.arrivalDate).getTime()
I need to calculate the total number of days (will always be a whole integer) between an arrival and departure date. These dates are strings, structured as 'YYYY-MM-DD'.
How do I go about this?
You can use regexp OR a much simpler approach would be to become familiar with MomentJS API that lets you deal with dates in JS very smoothly (works in Node and browser)
http://momentjs.com/
It does add another tool to your toolbox, but as soon as you are manipulating dates, it is definetely worth it IMHO.
Way to go with MomentJS :
var depDate = moment(response.departureDate);
var arrDate = moment(response.arrivalDate);
var nbDays = depDate.diff(arrDate, 'days');
Look at the Miles' answer here
Just change it to:
function parseDate(str) {
var mdy = str.split('-')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daydiff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
and use:
daydiff(parseDate(response.departureDate), parseDate(response.arrivalDate));
You can use RegEx to change them.
new Date(response.departureDate.replace(/-/g, "/")).getTime()
- new Date(response.arrivalDate.replace(/-/g, "/")).getTime()
So the RegEx .replace(/-/g, "/") will replace all the - to /, and JavaScript will be able to read it right.
I hope this example help for you
Apart from .diff(), you could also use moment durations: http://momentjs.com/docs/#/durations/
Example Fiddle: https://jsfiddle.net/abhitalks/md4jte5d/
Example Snippet:
$("#btn").on('click', function(e) {
var fromDate = $('#fromDate').val(),
toDate = $('#toDate').val(),
from, to, druation;
from = moment(fromDate, 'YYYY-MM-DD'); // format in which you have the date
to = moment(toDate, 'YYYY-MM-DD'); // format in which you have the date
/* using duration */
duration = moment.duration(to.diff(from)).days(); // you may use duration
/* using diff */
//duration = to.diff(from, 'days') // alternatively you may use diff
/* show the result */
$('#result').text(duration + ' days');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
From: <input id="fromDate" type='date' />
To: <input id="toDate" type='date' />
<button id="btn">Submit</button><hr />
<p id="result"></p>
You can use something like this
function countDays(date1, date2)
{
var one_day=1000*60*60*24;
return Math.ceil((date1.getTime()- date2.getTime()) /one_day);
}
countDays(new Date(response.departureDate), new Date(response.arrivalDate));

JavaScript - Validate Date

I have an HTML text field. I want to validate via JavaScript that the value entered is a valid date in the form of "MM/DD/YY" or "MM/D/YY" or "MM/DD/YYYY" or "MM/D/YYYY". Is there a function that does this?
I sort of assumed there was something like isNaN but I don't see anything. Is it true that JavaScript can't validate dates?
You could use javascript's own Date object to check the date. Since the date object allows some mucking around with the month and day values (for example March 32 would be corrected to April 1), you can just check that the date you create matches the one you put in. You could shorten this if you want, but it's longer for clarity.
function checkDate(m,d,y)
{
try {
// create the date object with the values sent in (month is zero based)
var dt = new Date(y,m-1,d,0,0,0,0);
// get the month, day, and year from the object we just created
var mon = dt.getMonth() + 1;
var day = dt.getDate();
var yr = dt.getYear() + 1900;
// if they match then the date is valid
if ( mon == m && yr == y && day == d )
return true;
else
return false;
}
catch(e) {
return false;
}
}
Is it true that JavaScript can't validate dates?
No.
Is there a function that does this?
No.
You will need to write your own validation function to parse the date format (regex comes to mind) and then determine if it is valid within your specific criteria.
Check out http://momentjs.com/. Using it, this snippet
moment(yourCandidateString, 'MM-DD-YYYY').isValid()
should do the job.
This is what I use to validate a date.
Date.parse returns NaN for invalid dates.
This supports both date-only and date+time formats.
Hope this helps.
var msg;
var str = "2013-12-04 23:10:59";
str = "2012/12/42";
var resp = Date.parse(str);
if(!isNaN(resp)) { msg='valid date'; } else { msg='invalid date'; }
console.log(msg);
If you want to venture into the realms of JQuery there are plenty of validation plugins that include date validation. This plugin is one I've used a few times and has served me well.
I use Bootstrap Datepicker. One of the options with the text box disabled should do the trick.
http://www.eyecon.ro/bootstrap-datepicker/
<input type="text" id="dateinput"/>
<script type="text/javascript">
$(#"dateinput").datepicker({
buttonImage: "images/calendar.png",
dateFormat: "yyyy-MMM-dd"
});
function validateDate() {
if ($(#"dateinput").val().trim() == "") {
// Is a blank date allowed?
return true;
}
var oldVal = $(#"dateinput").val(); // Current value in textbox
// Now use jQueryUI datepicker to try and set the date with the current textbox value
$(#"dateinput").datepicker("setDate",$(#"dateinput").val());
// Check if the textbox value has changed
if (oldVal != $(#"dateinput").val()) {
// The datepicker will set something different if the date is invalid
$(#"dateinput").val(oldVal); // Set the textbox back to the invalid date
alert ("date was invalid");
return false;
} else {
// If nothing changed, the date must be good.
return true;
}
}
</script>
There does not appear to be a build-in function which does that. However, this code is probably what you're looking for:
<script type="text/javascript">
/**--------------------------
//* Validate Date Field script- By JavaScriptKit.com
//* For this script and 100s more, visit http://www.javascriptkit.com
//* This notice must stay intact for usage
---------------------------**/
function checkdate(input){
var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval=false
if (!validformat.test(input.value))
alert("Invalid Date Format. Please correct and submit again.")
else{ //Detailed check for valid date ranges
var monthfield=input.value.split("/")[0]
var dayfield=input.value.split("/")[1]
var yearfield=input.value.split("/")[2]
var dayobj = new Date(yearfield, monthfield-1, dayfield)
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
else
returnval=true
}
if (returnval==false) input.select()
return returnval
}
</script>
Source: http://www.javascriptkit.com/script/script2/validatedate.shtml
Have you googled for something like javascript date validation? It shows up some good information, and a working code example here.
I suggest you a couple of solutions.
guide the user input with a date picker. This way you can control the input format. jQueryui datepicker is a popular implementation.
use a js library to manage datetime data type (not an actual datatype in Javascript!!). I suggest you date.js.
Similar to this answer, Date can be used to check if the parsed version of the string corresponds to the original date string.
> datestring_valid = "2020-02-29";
> parsed_Date = new Date(datestring_valid);
> parsed_Date.toISOString().slice(0,10) == datestring_valid;
true
> datestring_invalid = "2021-02-29";
> parsed_Date = new Date(datestring_invalid);
> parsed_Date.toISOString().slice(0,10) == datestring_invalid;
false
NB: This requires the date string to be ISO formatted.
The reason this works is, that Date parses some invalid dates into something valid as in the example above. However, supplying "2020-01-32" into Date will result in the result being "Invalid Date" that isNaN.
A function that handles all of this is the following:
function isValidDateString(datestring) {
parsed_Date = new Date(datestring);
return (parsed_Date.toISOString().slice(0,10) == datestring) && !isNaN(parsed_Date)
};
> isValidDateString(datestring_valid)
true
> isValidDateString(datestring_invalid)
false

Categories

Resources