I am trying to set the start and end date of a date range of a datepicker(), where the starting date of the range is 7 days in the past and the ending date is yesterday.
Currently I have it working so that the starting date of the range is 7 days in the past however I don't know how to set the ending date to yesterday.
I have tried the following, but it doesn't work as I expect it to:
var mindate = new Date();
mindate.setDate(mindate.getDate() - 7);
$('#date').datepicker({
language: 'en',
range : true,
minDate : mindate,
maxDate : new Date() - 1, //I guess the problem is here
multipleDates: true,
multipleDatesSeparator: " - "
})
One approach would be to compute a maxdate using the same technquie as you have used to compute mindate and then apply that max date value to the maxData parameter of the datepicker() instance:
var mindate = new Date();
mindate.setDate(mindate.getDate() - 7);
/* Compute max date of "yesterday" using same method as
min date */
var maxdate = new Date();
maxdate.setDate(maxdate.getDate() - 1);
$('#date').datepicker({
language: 'en',
range : true,
minDate : mindate,
maxDate : maxdate, /* Apply max date to date picker */
multipleDates: true,
multipleDatesSeparator: " - "
});
The datepicker() plugin also allows you to specify minDate and maxDate via the number of days relative to today's date. That means you can achieve the same result as shown above without needing to calculate mindate and maxdate by specifying minDate and maxDate as shown:
$('#date').datepicker({
language: 'en',
range : true,
minDate : -7, /* 7 days ago */
maxDate : -1, /* Yesterday */
multipleDates: true,
multipleDatesSeparator: " - "
});
minDate and maxDate can the amount of days from today.
https://api.jqueryui.com/datepicker/#option-minDate
So all you need to do is
minDate: -1,
maxDate: -7,
In HTML5 you already have a <input type="date"> so you don't need any kind of jQuery.
Unless you need support for legacy browsers I can only recommend using HTML5 over jquery.
HTML
<input type="date" id="date">
Vanilla JS
function getHtmlDateString(date) {
var dd = date.getDate();
var mm = date.getMonth()+1; //January is 0!
var yyyy = date.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
return yyyy+'-'+mm+'-'+dd;
}
var min = new Date();
min.setDate(min.getDate()-7);
document.getElementById("date").setAttribute("min", getHtmlDateString(min));
var max = new Date();
max.setDate(max.getDate()-1);
document.getElementById("date").setAttribute("max", getHtmlDateString(max));
JSFiddle: https://jsfiddle.net/hmqe4sb6/
Hello I have this imput Date, with small changes:
- days available from tomorrow
- default day tomorrow
- and date format dd/mm/yyyy
$(document).ready(function() {
var now = new Date();
var day = ("0" + (now.getDate() + 1)).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear() + "-" + (month) + "-" + (day);
$('.dateD').val(today).attr("min", today);
});
But I need the month as a name not a number, January, February, etc...
so the date should be: 04/February/2017
here the example:
http://jsbin.com/rovuliyere/edit?html,js,output
thank you!
You can use Internationalization API for that. This snippet only work on modern browsers. See browser compability
var locale = "en-us",
month = now.toLocaleString(locale, { month: "long" });
Working example: http://jsbin.com/bifagurege/1/edit?html,js,output
you can try datepicker for formatting:
https://jqueryui.com/datepicker/
so the date should be: 04/February/2017
It's impossible to set(change) a custom format of <input type="date" />. It requires a full-date format equal to: yyyy-mm-dd
To render current Date in the format dd/Month/yy use the following short solution with Date.prototype.toLocaleString() :
var now = new Date(),
day = ("0" + (now.getDate())).slice(-2),
// the first argument 'en-us' is a locale(you can adjust it)
today = day + '/'
+ now.toLocaleString('en-us', { month: "long" })
+ "/" + now.getFullYear();
$('.dateD').val(today).attr("min", today);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="dateD" type="text" readonly='true'/>
I have date in Javascript
Sun Feb 15 2015 08:02:00 GMT+0200 (EET)
how I can to set in format 'dd/mm/yyyy hh:mm:ss' into datetime picker?
If I set like this:
dateStart
Sun Feb 15 2015 08:02:00 GMT+0200 (EET)
$('#dateTimeStart').datetimepicker('setDate', dateStart);
Error parsing the date/time string: Missing number at position 10
date/time string = 02-15-2015 08:02:00
timeFormat = HH:mm
dateFormat = mm-dd-yyyy
$('#dateTimeStart').datetimepicker({
dateFormat: 'yy-dd-mm'
timeFormat: "hh:mm:ss"
});
You have to format date that you have. You can do it with help of function that you can grab here.
Usage:
<script>
document.write($.format.date("Sun Feb 15 2015 08:02:00", "dd/mm/yyyy hh:mm:ss"));
</script>
It's small and really nice solution that can help you to resolve your issue.
You're looking for a format like
jQuery('#dateTimeStart').datetimepicker({
format:'d/m/Y H:i:s'
});
According to the DateTimePicker documentation at http://xdsoft.net/jqplugins/datetimepicker/, the 'format' string is based on the PHP date format strings, which you can read up on at http://php.net/manual/en/function.date.php. Note in particular they use just one letter to represent multiple numbers (e.g. 'd' instead of 'dd')
use below javascript code to change formate
var date = new Date('Sun Feb 15 2015 08:02:00 GMT+0200');
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var fulldate = day+'/'+(month+1)+'/'+year+' '+hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);
see working copy of fiddle
you can create function which return date in format
function convertdate(param){
var date = new Date(param);
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
return fulldate = day+'/'+(month+1)+'/'+year+' '+hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);
}
alert(convertdate('Sun Feb 15 2015 08:02:00 GMT+0200'));
I change format of date from server in this : '02/15/2015 08:02:00 AM'
and then I parse this string and create new date:
var dateString ='02/15/2015 08:02:00 AM';
var dateStart = new Date(Date.parse(dateString, "mm/dd/yyyy hh:mm:ss"));
$('#dateTimeStart').datetimepicker('setDate', dateStart);
I want to select any date and convert it to same date of next upcoming month. For example- I select 1st jun 2014 then it show 1st july 2014 and so on..
Fiddle
HTML
<input type='text' id='txtDate' readonly='true' />
<input type='button' id='btnConvert' value='Convert' /><br/>
Current Date : <span id='spnCurrentDate'></span><br/>
Next Month Date : <span id='spnNewDate'></span>
JS
$("#txtDate").datepicker({
changeMonth: true
});
$("#btnConvert").click(function(){
$("#spnCurrentDate").html($("#txtDate").val());
$("#spnNewDate").html($("#txtDate").val());
If you are just asking how to add one month to a Date object, you can't just add one to the month as 2014-01-31 + 1 month -> 2014-02-31 which is converted to 2014-03-03.
So if you roll over to the following month, you probably want to set the day to the last of the previous month:
function addOneMonth(date) {
var o = new Date(+date);
date.setMonth(date.getMonth() + 1);
// If have rolled over an extra month, set to last
// day of previous month
if (date.getDate() != o.getDate()) {
date.setDate(0);
}
return date;
}
addOneMonth(new Date(2014,0,31)); // 2014-02-28
or not…
DEMO here
var date1 = new Date();
date1.setMonth(date1 .getMonth() + 1);
now date1 is an object holding a date which is 1 months later
If you want to set it to the jQuery UI DatePickers, you can do this
$("#txtDate").datepicker({
changeMonth: true
});
$("#btnConvert").click(function(){
var date1 = new Date($("#txtDate").val());
date1.setMonth(date1 .getMonth() + 1);
$("#txtDate").datepicker("setDate", date1 );
});
Try This Demo : http://jsfiddle.net/PQfDc/151/
$("#txtDate").datepicker({
changeMonth: true,
minDate:'0',
onClose: function( selectedDate ) {
var d = new Date(selectedDate)
d.setMonth(d.getMonth() + 1);
$("#txtDate").datepicker("setDate", d );
$("#spnSelectedDate").text(selectedDate);
$("#spnNewDate").text($('#txtDate').val());
}
});
$("#txtDate1").datepicker({
changeMonth: true,
minDate:'0'
});
$("#btnConvert").click(function(){
var d1 = new Date($("#txtDate1").val());
var date = d1.getDate();
var month = d1.getMonth()+1;
var year = d1.getFullYear();
var newDate = month + "/" + date + "/" + year
$("#spnSelectedDate1").text($("#txtDate1").val());
$("#spnNewDate1").text(newDate);
});
alert(dateObj) gives Wed Dec 30 2009 00:00:00 GMT+0800
How to get date in format 2009/12/30?
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = year + "/" + month + "/" + day;
or you can set new date and give the above values
new Date().toISOString()
"2016-02-18T23:59:48.039Z"
new Date().toISOString().split('T')[0];
"2016-02-18"
new Date().toISOString().replace('-', '/').split('T')[0].replace('-', '/');
"2016/02/18"
new Date().toLocaleString().split(',')[0]
"2/18/2016"
var dt = new Date();
dt.getFullYear() + "/" + (dt.getMonth() + 1) + "/" + dt.getDate();
Since month index are 0 based you have to increment it by 1.
Edit
For a complete list of date object functions see
Date
getMonth()
Returns the month (0-11) in the specified date according to local time.
getUTCMonth()
Returns the month (0-11) in the specified date according to universal time.
Why not using the method toISOString() with slice or simply toLocaleDateString()?
Beware that the timezone returned by toISOString is always zero UTC offset, whereas in toLocaleDateString it is the user agent's timezone.
Check here:
const d = new Date() // today, now
// Timezone zero UTC offset
console.log(d.toISOString().slice(0, 10)) // YYYY-MM-DD
// Timezone of User Agent
console.log(d.toLocaleDateString('en-CA')) // YYYY-MM-DD
console.log(d.toLocaleDateString('en-US')) // M/D/YYYY
console.log(d.toLocaleDateString('de-DE')) // D.M.YYYY
console.log(d.toLocaleDateString('pt-PT')) // DD/MM/YYYY
I would suggest you to use Moment.js http://momentjs.com/
Then you can do:
moment(new Date()).format("YYYY/MM/DD");
Note: you don't actualy need to add new Date() if you want the current TimeDate, I only added it as a reference that you can pass a date object to it. for the current TimeDate this also works:
moment().format("YYYY/MM/DD");
2021 ANSWER
You can use the native .toLocaleDateString() function which supports several useful params like locale (to select a format like MM/DD/YYYY or YYYY/MM/DD), timezone (to convert the date) and formats details options (eg: 1 vs 01 vs January).
Examples
new Date().toLocaleDateString() // 8/19/2020
new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 08/19/2020 (month and day with two digits)
new Date().toLocaleDateString('en-ZA'); // 2020/08/19 (year/month/day) notice the different locale
new Date().toLocaleDateString('en-CA'); // 2020-08-19 (year-month-day) notice the different locale
new Date().toLocaleString("en-US", {timeZone: "America/New_York"}); // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)
new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}); // 09 (just the hour)
Notice that sometimes to output a date in your specific desire format, you have to find a compatible locale with that format.
You can find the locale examples here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all
Please notice that locale just change the format, if you want to transform a specific date to a specific country or city time equivalent then you need to use the timezone param.
var date = new Date().toLocaleDateString()
"12/30/2009"
info
If a 2 digit month and date is desired (2016/01/01 vs 2016/1/1)
code
var dateObj = new Date();
var month = ('0' + (dateObj.getMonth() + 1)).slice(-2);
var date = ('0' + dateObj.getDate()).slice(-2);
var year = dateObj.getFullYear();
var shortDate = year + '/' + month + '/' + date;
alert(shortDate);
output
2016/10/06
fiddle
https://jsfiddle.net/Hastig/1xuu7z7h/
credit
More info from and credit to this answer
more
To learn more about .slice the try it yourself editor at w3schools helped me understand better how to use it.
let dateObj = new Date();
let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());
For reference you can see the below details
new Date().getDate() // Return the day as a number (1-31)
new Date().getDay() // Return the weekday as a number (0-6)
new Date().getFullYear() // Return the four digit year (yyyy)
new Date().getHours() // Return the hour (0-23)
new Date().getMilliseconds() // Return the milliseconds (0-999)
new Date().getMinutes() // Return the minutes (0-59)
new Date().getMonth() // Return the month (0-11)
new Date().getSeconds() // Return the seconds (0-59)
new Date().getTime() // Return the time (milliseconds since January 1, 1970)
let dateObj = new Date();
let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());
console.log(myDate)
Use the Date get methods.
http://www.tizag.com/javascriptT/javascriptdate.php
http://www.htmlgoodies.com/beyond/javascript/article.php/3470841
var dateobj= new Date() ;
var month = dateobj.getMonth() + 1;
var day = dateobj.getDate() ;
var year = dateobj.getFullYear();
Nice formatting add-in: http://blog.stevenlevithan.com/archives/date-time-format.
With that you could write:
var now = new Date();
now.format("yyyy/mm/dd");
EUROPE (ENGLISH/SPANISH) FORMAT
I you need to get the current day too, you can use this one.
function getFormattedDate(today)
{
var week = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var day = week[today.getDay()];
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
var hour = today.getHours();
var minu = today.getMinutes();
if(dd<10) { dd='0'+dd }
if(mm<10) { mm='0'+mm }
if(minu<10){ minu='0'+minu }
return day+' - '+dd+'/'+mm+'/'+yyyy+' '+hour+':'+minu;
}
var date = new Date();
var text = getFormattedDate(date);
*For Spanish format, just translate the WEEK variable.
var week = new Array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado');
Output: Monday - 16/11/2015 14:24
With the accepted answer, January 1st would be displayed like this: 2017/1/1.
If you prefer 2017/01/01, you can use:
var dt = new Date();
var date = dt.getFullYear() + '/' + (((dt.getMonth() + 1) < 10) ? '0' : '') + (dt.getMonth() + 1) + '/' + ((dt.getDate() < 10) ? '0' : '') + dt.getDate();
Here is a cleaner way getting Year/Month/Day with template literals:
var date = new Date();
var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;
console.log(formattedDate);
It's Dynamic It will collect the language from user's browser setting
Use minutes and hour property in the option object to work with them..
You can use long value to represent month like Augest 23 etc...
function getDate(){
const now = new Date()
const option = {
day: 'numeric',
month: 'numeric',
year: 'numeric'
}
const local = navigator.language
labelDate.textContent = `${new
Intl.DateTimeFormat(local,option).format(now)}`
}
getDate()
You can simply use This one line code to get date in year-month-date format
var date = new Date().getFullYear() + "-" + new Date().getMonth() + 1 + "-" + new Date().getDate();
ES2018 introduced regex capture groups which you can use to catch day, month and year:
const REGEX = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;
const results = REGEX.exec('2018-07-12');
console.log(results.groups.year);
console.log(results.groups.month);
console.log(results.groups.day);
Advantage of this approach is possiblity to catch day, month, year for non-standard string date formats.
Ref. https://www.freecodecamp.org/news/es9-javascripts-state-of-art-in-2018-9a350643f29c/
One liner, using destructuring.
Makes 3 variables of type string:
const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-')
Makes 3 variables of type number (integer):
const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-').map(x => parseInt(x, 10))
From then, it's easy to combine them any way you like:
const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-');
const dateFormatted = `${year}/${month}/${day}`;
I am using this which works if you pass it a date obj or js timestamp:
getHumanReadableDate: function(date) {
if (date instanceof Date) {
return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
} else if (isFinite(date)) {//timestamp
var d = new Date();
d.setTime(date);
return this.getHumanReadableDate(d);
}
}