I only want the date range to be selectable for future days and the first day should be before or the same day as the 2nd day to create a date range.
Input is
first date: 01/23/2020
second date: 03/19/2020
currdate: 12/11/2019
var curdate = month + "/" + day + "/" + year;
if(smsBlackoutFirstDateSelect.value > smsBlackoutSecondDateSelect.value){
alert("second date is before first date");
} else if(smsBlackoutFirstDateSelect.value <= curdate){
alert("first date is on or before today" + " " + smsBlackoutFirstDateSelect.value + " " +
smsBlackoutSecondDateSelect.value + " " + curdate);
} else {
some success function;
}
Output is :
first date is on or before today 01/23/2020 03/19/2020 12/11/2019
any idea why it isn't comparing years?
if you are referring to the comparison of curdate with smsBlackoutFirstDateSelect.value,
curdate is not a date field.
if you want date comparison to convert it to date by
var d1 = new Date(curdate);
and use it
you can refer below question
Compare two dates with JavaScript
I see that you're using a string to represent the date. This won't work well. Ideally, we should use javascript Date variables to handle the sorting as needed.
Try something like this and see how it compares.
Example:
3 numbers specify year, month, and day:
var curdate = new Date(2018, 11, 24);
I can't see how smsBlackoutFirstDateSelect is defined. It may also need to be casted to Dates() separately. See the other methods to create a Date() referenced below.
Reference: https://www.w3schools.com/js/js_dates.asp
Related
I have a date string like this 20/09/2018 12:00 AM. I need to stop to put the previous date than today. I have searched the web for it, but no answer found with this format.
I need the default date format of JavaScript so that I can compare with new Date() value. When I use the following format it show the message that says invalid date because of my dd/MM/yyyy hh:mm tt format.
alert(new Date("20/09/2018 12:00 AM"));
Igor recommended using moment.js to solve this — it is a widely used date/time library.
With moment.js you can do this:
var m = moment("20/09/2018 3:14 PM", "DD/MM/YYYY h:mm a");
var d = m.toDate();
The first line creates a "moment" object by parsing the date according to the format string specified as the second argument. See http://momentjs.com/docs/#/parsing/
The second line gets the native javascript Date object that the moment object encapsulates; however, moment can do so many things you may not need to get back that native object.
See the moment docs.
Your format isn't valid, thus you're getting invalid date error. So, using your format(dd/MM/yyyy hh:mm tt) we'll grab the year, month, day, hours and the minutes, then we'll reformat it as an acceptable format by the Date constructor and create a Date instance.
Here's a function that do all what being said and returns a Date instance which you can compare it with another Date instance:
function convertToDate(str) {
// replace '/' with '-'
str = str.replace(/\//ig, '-');
/**
* extracting the year, month, day, hours and minutes.
* the month, day and hours can be 1 or 2 digits(the leading zero is optional).
* i.e: '4/3/2022 2:18 AM' is the same as '04/03/2022 02:18 AM' => Notice the absence of the leading zero.
**/
var y = /\-([\d]{4})/.exec(str)[1],
m = /\-([\d]{2}|[\d])/.exec(str)[1],
d = /([\d]{2}|[\d])\-/.exec(str)[1],
H = /\s([\d]{2}|[\d]):/.exec(str)[1],
i = /:([\d]{2})/.exec(str)[1],
AMorPM = /(AM|PM)/.exec(str)[1];
// return a Date instance.
return new Date(y + '-' + m + '-' + d + ' ' + H + ':' + i + ' ' + AMorPM)
}
// testing...
var str1 = '20/09/2018 12:00 AM';
var str2 = '8/2/2018 9:00 PM'; // leading zero is omitted.
console.log(convertToDate(str1));
console.log(convertToDate(str2));
The Date depends on the user's/server's location, two users may have
different results.
Learn more
about Date.
Hope I pushed you further.
I want to filter data by current month (maybe additionally add next month data). I don't know how to go from the beginning.
In theory I think I could compare current month and month date from my data and then to display data only if two months variables match.
I thought I should start like this:
var myDate = new Date();
var thisMonth = new Date(myDate);
thisMonth.setMonth(myDate.getMonth()+1);
var nextMonth = new Date(myDate);
nextMonth.setMonth(myDate.getMonth()+2);
Thank you in advance for any kind of help!
Additional detailed explanation:
I copied SharePoint 2013 list whose data I displayed on SharePoint site page.
In content editor web part I wrote javascript code to show that list as a table.
I have two date columns (from/until) but they are displayed in table as YYYY-MM-DD HH:MM:SS. Looks to me like ISO date format. I saw several examples how to convert in js that type of date into date type like DD.MM.YYYY. None worked for me or I didn't know how to do it correctly. So I created calculated field that will present date type as text/string, after this I managed to show date on js table the way I wanted.
You should not parse strings with the Date constructor (or Date.parse, they are equivalent for parsing) as it's largely implementation dependent and notoriously unreliable.
I have two date columns (from/until) but they are displayed in table as YYYY-MM-DD HH:MM:SS. Looks to me like ISO date format.
Almost. The extended format is YYYY-MM-SSTHH:MM:SS, the T can be replaced by a space on agreement between parties exchanging the date but it's not strictly correct. If the timezone is omitted, it's treated as a "local" date (i.e. the host timezone offset is used in calculating the moment in time that it represents).
According to ECMA-262, if the format is not correct, browsers can either:
Treat it as invalid ISO 8601 and return an invalid date
Treat it as not ISO 8601 and fall back to whatever parsing algorithm they wish to use
So given:
new Date('2017-01-01 23:12:12')
Firefox returns a Date for 1 Jan 2017 23:12:12 in the host time zone, Safari returns an invalid date. Both are consistent with the standard.
So if you need a Date object, you should parse the string manually using either a library (e.g. fecha.js or moment.js) or a simple function.
But anyway, you don't need to parse the strings to a Date to reformat the string, just use string methods and avoid Date parsing vagaries completely.
function filterCurrentMonth() {
// Create string for comparison
var d = new Date();
var currentMonth = d.getFullYear() + '-' + ('0' + (d.getMonth()+1)).slice(-2);
// Hide rows that don't have string in the first cell
var rows = document.getElementById('t0').rows;
[].forEach.call(rows, function(row) {
if (row.cells[0].textContent.indexOf(currentMonth) == -1) {
row.style.display = 'none';
} else {
row.style.display = '';
}
});
}
function filterNone() {
var rows = document.getElementById('t0').rows;
[].forEach.call(rows, function(row) {
row.style.display = '';
});
}
#t0 {
font-size: 60%;
}
<button onclick="filterCurrentMonth()">Show only current month rows</button>
<button onclick="filterNone()">Show all rows</button>
<table id="t0">
<tr><td>2017-01-01 23:12:12<tr><td>2017-02-01 23:12:12<tr><td>2017-05-01 23:12:12
<tr><td>2017-03-01 23:12:12<tr><td>2017-04-01 23:12:12<tr><td>2017-12-01 23:12:12
<tr><td>2017-10-01 23:12:12<tr><td>2017-11-01 23:12:12<tr><td>2017-06-01 23:12:12
<tr><td>2017-07-01 23:12:12<tr><td>2017-09-01 23:12:12<tr><td>2017-08-01 23:12:12
<tr><td>2017-01-01 23:12:12<tr><td>2017-02-01 23:12:12<tr><td>2017-05-01 23:12:12
<tr><td>2017-03-01 23:12:12<tr><td>2017-04-01 23:12:12<tr><td>2017-12-01 23:12:12
<tr><td>2017-10-01 23:12:12<tr><td>2017-11-01 23:12:12<tr><td>2017-06-01 23:12:12
<tr><td>2017-07-01 23:12:12<tr><td>
<!-- begin snippet: js hide: false console: true babel: false -->
23:12:122017-08-01 23:12:12
Similarly, if you want to reformat the string to be DD.MM.YYYY you can just reformat the string:
/* Format string in YYYY-MM-DD HH:mm:ss format to DD.MM.YYYY
** #param {string} s - string in YYYY-MM-DD HH:mm:ss format
** #returns {string} in DD.MM.YYYY format
*/
function formatYMDtoDMY(s) {
var b = s.split(/\D/);
return b[2] + '.' + b[1] + '.' + b[0];
}
console.log(formatYMDtoDMY('2017-10-01 23:12:12'))
Note however that dates should use unambiguous formats like DD-MMM-YYYY, e.g. 01-Jan-2017. It only takes one more line of code for that. ;-)
Don't forget, getMonth() returns a Number, from 0 to 11, representing the month,
and Date make the date as object with methods and properties
There is a lot of examples here
var date = new Date('2010-10-11 00:00:00');
var formatDate = date.getDate() + '/'
+ (date.getMonth() + 1) + '/'
+ date.getFullYear();
console.log( formatDate );
So you can always pass the date on any format but there some important moments you can read here:
Converting string to date in js
Are you asking?
I don't know how to go from the beginning.
You could get the beginning from current month and the last date of next month by following code:
<html>
<script>
var myDate = new Date();
var thisMonth = new Date(myDate.getFullYear(), myDate.getMonth(), 1);
var nextMonth = new Date(myDate.getFullYear(), myDate.getMonth() + 2, 0);
console.log("Date start: " + thisMonth);
console.log("Date end: " + nextMonth);
console.log("Formatted date start: " + formatDate(thisMonth));
console.log("Formatted date end: " + formatDate(nextMonth));
function padLeft(n){
return ("00" + n).slice(-2);
}
function formatDate(){
var d = new Date,
dformat = [ d.getFullYear(),
padLeft(d.getMonth()+1),
padLeft(d.getDate())
].join('-')+
' ' +
[ padLeft(d.getHours()),
padLeft(d.getMinutes()),
padLeft(d.getSeconds())].join(':');
return dformat
}
</script>
</html>
I hope it helps you. Bye.
I am trying to prepopulate a date into an html "date" input field, but it ignores the values I try to pass:
<html>
...
<input id='date' type='date'>
...
</html>
<script>
...
var myDate = new Date();
$("#date").val(myDate);
...
I have also tried passing the date object as a string
var myDate = new Date().toDateString();
$("#date").val(myDate);
When I open the form, the date field is blank. If I eliminate the type="date" tag, the value shows up as a string, but then I don't have access to the datepicker. How do I pre-populate a date input and still have use of the datepicker? I'm stumped.
Thanks.
It must be set in ISO-format.
(function () {
var date = new Date().toISOString().substring(0, 10),
field = document.querySelector('#date');
field.value = date;
console.log(field.value);
})()
http://jsfiddle.net/GZ46K/
Why Not to Use toISOString()
The <input type='date'> field takes a value in ISO8601 format (reference), but you should not use the Date.prototype.toISOString() function for its value because, before outputting an ISO8601 string, it converts/represents the date/time to UTC standard time (read: changes the time zone) (reference). Unless you happen to be working in or want that time standard, you will introduce a bug where your date will sometimes, but not always, change.
Populate HTML5 Date Input from Date Object w/o Time Zone Change
The only reliable way to get a proper input value for <input type='date'> without messing with the time zone that I've seen is to manually use the date component getters. We pad each component according to the HTML date format specification (reference):
let d = new Date();
let datestring = d.getFullYear().toString().padStart(4, '0') + '-' + (d.getMonth()+1).toString().padStart(2, '0') + '-' + d.getDate().toString().padStart(2, '0');
document.getElementById('date').value = datestring;
/* Or if you want to use jQuery...
$('#date').val(datestring);
*/
<input id='date' type='date'>
Populate HTML5 Date & Time Fields from Date Object w/o Time Zone Change
This is beyond the scope of the original question, but for anyone wanting to populate both date & time HTML5 input fields from a Date object, here is what I came up with:
// Returns a 2-member array with date & time strings that can be provided to an
// HTML5 input form field of type date & time respectively. Format will be
// ['2020-12-15', '01:27:36'].
function getHTML5DateTimeStringsFromDate(d) {
// Date string
let ds = d.getFullYear().toString().padStart(4, '0') + '-' + (d.getMonth()+1).toString().padStart(2, '0') + '-' + d.getDate().toString().padStart(2, '0');
// Time string
let ts = d.getHours().toString().padStart(2, '0') + ':' + d.getMinutes().toString().padStart(2, '0') + ':' + d.getSeconds().toString().padStart(2, '0');
// Return them in array
return [ds, ts];
}
// Date object
let d = new Date();
// Get HTML5-ready value strings
let dstrings = getHTML5DateTimeStringsFromDate(d);
// Populate date & time field values
document.getElementById('date').value = dstrings[0]
document.getElementById('time').value = dstrings[1]
/* Or if you want to use jQuery...
$('#date').val(dstrings[0]);
$('#time').val(dstrings[1]);
*/
<input type='date' id='date'>
<input type='time' id='time' step="1">
Thank you j08691. That link was the answer.
To others struggling like me, when they say input is "yyyy-mm-dd" the MEAN it!
You MUST have 4 digits for the year.
You MUST have a dash and no spaces.
You MUST have 2 digits for day and month.
In my example myDate.getMonth for January would only return "1" (actually it returns "0" because for some reason javascript counts months from 0-11). To get this right I had to do the following:
var myDate, day, month, year, date;
myDate = new Date();
day = myDate.getDate();
if (day <10)
day = "0" + day;
month = myDate.getMonth() + 1;
if (month < 10)
month = "0" + month;
year = myDate.getYear();
date = year + "-" + month + "-" + day;
$("#date").val(date);
I hope this helps others not waste hours like I did testing this before October or before the 10th of the month! LOL
Here is an answer based on Robin Drexlers but in local time.
//Get the local date in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 10);
//Set the field value
var field = document.querySelector('#date');
field.value = datestr;
If it's a datetime field you're modifying (as opposed to just the date) don't forget to add the time T00:00, or change the substring to 16 characters for example:
//Get the local date and time in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 16);
//Set the field value
var field = document.querySelector('#datetime');
field.value = datestr;
This below code populates the local date . The accepted answer populates UTC date.
var date = new Date();
field = document.querySelector('#date-id');
var day = date.getDate();
if(day<10){ day="0"+day;}
var month = date.getMonth()+1;
if(month<10){ month="0"+month;}
field.value = date.getFullYear()+"-"+month+"-"+day;
I don't have the reputation points to comment on another answer, so I'll just add a new answer. And since I'm adding an answer, I'll give more details than I would've in a comment.
There's an easier way to zero pad than all of the juggling that everyone is doing here.
var date = new Date();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var year = date.getFullYear();
var htmlDate = year + '-' + month + '-' + day;
console.log("Date: " + htmlDate);
Today, the output would be
Date: 2020-01-07
The code is building a dynamic string by prepending a quoted zero, then taking the last 2 characters with slice(-2). This way, if the zero makes it 01, the last 2 are 01. If the zero makes it 011, then the last two are 11.
As for the month starting at zero silliness, you can also add 1 dynamically before prepending the zero and everything still works. You just have to do the math operation before turning it into a string.
As a side note, I've noticed that when you update a date field, you have to hide the field before setting the value and show it after setting. I don't do this often enough, so I have to re-struggle each time I need to deal with it. Hopefully this will help someone from the future.
waves to future people
Lets say there are two textboxes, one to enter in a date and the other to enter in time. Below is an example:
<p><strong>Date:</strong> <input type="text" id="datetxt"></p>
Example of how date is displayed: 25-05-1995
<p><strong>Time:</strong> <input type="text" id="timetxt"></p>
Example of how time is displayed: 14:25
Can someone suggest a way in javascript to compare values of the date and time from the textboxes to the current date and time so if the current date and time is past the date and time entered in the textboxes, then it should display and alert?
Try this
var dateParts = document.getElementById("datetxt").value.split("-");
var timeParts = document.getElementById("timetxt").value.split(":");
var valueDate = new Date(dateParts[2], (dateParts[1] - 1) ,dateParts[0], timeParts[0], timeParts[1]);
if( (new Date).getTime() > valueDate .getTime() )
{
alert("passed");
}
Live example: http://jsfiddle.net/TJEMr/
You need to massage your date string into a compatible date format:
//datetxt textbox value, split on dashes
var date = "25-05-1995".split("-"),
//timetxt textbox value
time = "14:25",
//put it into format: YYYY-MM-DDThh:mm and creates a date object from it
dateObj = new Date(date[2] + '-' + date[1] + '-' + date[0] + 'T' + time);
//if today is greater than we have passed that DateTime
if(new Date() > dateObj) {
alert("After entered date");
} else {
alert("Not passed yet!");
}
Working example: jsFiddle
I would like to have an input field with a button next to it.
On the input field I will enter a date like this:
2011-07-08
And when I hit the button it should read the time that has been entered on the input field and subtract it with 3 months and one day.
Is this possible?
Thanks in advance
Yes. First you read the date and you convert to a date object
var dateString = document.getElementById('id of your field').value,
date = new Date(dateString);
then you subtract 91 days and output the result
date.setDate(date.getDate() - 91);
alert(date.toString());
Here I assume for simplicity that you actually want 91 days and not 3 months and one day. If you want three months and one day you will do
date.setMonth(date.getMonth() - 3);
date.setDate(date.getDate() - 1);
alert(date.toString());
The Date object will take care of overflows, leap years and everything.
If you want to write it to same field, taking care of zeroes, you can do
function assureTwoDigits(number) {
if (number > 9) {
return '-' + number;
}
else {
return '-0' + number;
}
}
and change the last line to
document.getElementById('id of your field').value = date.getFullYear() + assureToDigits(date.getMonth()) + assureTwoDigits(date.getDate());
You can use Date objects (see here):
extract year, moth and day from the string (using a regular expression or splitting by '-')
buid a new Date object with that data
subtract the date interval
build the string back
The simplest way would be to split it into an array, then use a couple of if/else statements:
var date = (whatever you're pulling the date in as).split('-');
if (date[1] > 3)
date[1] = date[1] - 3;
else
date[0] = date[0] - 1;
var dateOverflow = date[1]-3;
date[1] = 12 - dateOverflow;
And then the same for the days.
Yes, it's possible and it's the most clean if you can do it without some arcane regex magic. Start by converting the date to a Date object:
// this will get you a date object from the string:
var myDate = new Date("2011-07-08");
// subtract 3 months and 1 day
myDate.setMonth(myDate.getMonth()-3);
myDate.setDay(myDate.getMonth(), myDate.getDay()-1);
// And now you have the day and it will be correct according to the number of days in a month etc
alert(myDate);