javascript date increment - javascript

I want to set a text box with a date (in dd/mm/yyyy format) 14 days ahead to current date in javascript . can any one help me regarding this ?

This should do it:
var myDate=new Date();
myDate.setDate(myDate.getDate()+14);
then
document.getElementById(YOUR_TEXTBOX_ID).value = myDate.getDate() + "/" +
(myDate.getMonth() + 1) + "/" + myDate.getFullYear();

Date.js is a handy script for all kinds of JavaScript date manipulation. I've used it to make many date-based interfaces, including calendar controls.

Like Deodeus suggested, use Date.js:
var myDate = Date.today().add(14).days();
document.getElementById('mytextbox').value = myDate.toString('dd/MM/yyyy');

Following is the function to increment date by one day in javascript.
function IncrementDate(date) {
var tempDate = new Date(date);
tempDate.setDate(tempDate.getDate() + 1);
return tempDate;
}
Function calling...
var currentDate = new Date();
var IncrementedDate = IncrementDate(currentDate);

Related

How to change date format using jQuery?

I have a date in a format like this fecha2.value = '2014-01-06', but I want to change the format to this '01-06-14' using jQuery.
How can I do this?
You can use date.js to achieve this:
var date = new Date('2014-01-06');
var newDate = date.toString('dd-MM-yy');
Alternatively, you can do it natively like this:
var dateAr = '2014-01-06'.split('-');
var newDate = dateAr[1] + '-' + dateAr[2] + '-' + dateAr[0].slice(-2);
console.log(newDate);
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
curr_year = curr_year.toString().substr(2,2);
document.write(curr_date+"-"+curr_month+"-"+curr_year);
You can change this as your need..
You don't need any date-specific functions for this, it's just string manipulation:
var parts = fecha2.value.split('-');
var newdate = parts[1]+'-'+parts[2]+'-'+(parseInt(parts[0], 10)%100);
I dont think you need to use jQuery at all, just simple JavaScript...
Save the date as a string:
dte = fecha.value;//2014-01-06
Split the string to get the day, month & year values...
dteSplit = dte.split("-");
yr = dteSplit[0][2] + dteSplit[0][3]; //special yr format, take last 2 digits
month = dteSplit[1];
day = dteSplit[2];
Rejoin into final date string:
finalDate = month+"-"+day+"-"+year
In most projects you want to use moment.js library along with datepicker and datetimepickers .
It doesnt look that verbose. For example
let dateString_ = moment('2023-01-17T13:39:48.530801Z').format("YYYY-MM-DD HH:mm");
for 2023-01-17 18:39
Formatting rules are here

Setting format and value in input type="date"

Is there any way to set the format of <input type="date" /> ? if no then how can i set date in this field using JavaScript in the default format of type="date". how can i get what will be the format of this field?
EDIT :
Actually i want to show native date-picker of mobile device that's why i picked this type of input. if is there any alternate for that field that also will b good to have.
Sorry if i said anything stupid. Please guide me
The format is YYYY-MM-DD. You cannot change it.
$('#myinput').val('2013-12-31'); sets value
new Date().toISOString().split('T')[0];
try this :)
function getDefaultDate(){
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
return today;
}
$(document).ready(function(){
$("#dateid").val( getDefaultDate());
});
Canadian locale happens to follow the same format, too:
new Date().toLocaleDateString('en-CA')
Easier than the above is
var today = new Date().toISOString().substring(0,10); # "2013-12-31"
It's ugly, but it works. :/
var today = new Date().toLocaleString('en-GB').split(' ')[0].split('/').reverse().join('-');
Please check this https://stackoverflow.com/a/9519493/1074944 and try this way also $('input[type="date"]').datepicker().prop('type','text'); check the demo
I think this can help
function myFormatDateFunction(date, format) {
...
}
jQuery('input[type="date"]')
.each(function(){
Object.defineProperty(this,'value',{
get: function() {
return myFormatDateFunction(this.valueAsDate, 'dd.mm.yyyy');
},
configurable: true,
enumerable : true
});
});
function getDefaultDate(curDate){
var dt = new Date(curDate);`enter code here`
var date = dt.getDate();
var month = dt.getMonth();
var year = dt.getFullYear();
if (month.toString().length == 1) {
month = "0" + month
}
if (date.toString().length == 1) {
date = "0" + date
}
return year.toString() + "-" + month.toString() + "-" + date.toString();
}
In function pass your date string.
#cOnstructOr provided a great idea, but it left a comma in place
var today = new Date().toLocaleString('en-GB').split(' ')[0].slice(0,-1).split('/').reverse().join('-');
fixes that
What you want to do is fetch the value from the input and assign it to a new Date instance.
let date = document.getElementById('dateInput');
let formattedDate = new Date(date.value);
console.log(formattedDate);
Here is a simple answer,
Since this is a string, we can use Javascript String slice method to rearrange the characters
<input type="date" id="idate" name="tno"><br>
<button onclick="run()">Run</button>
<p id="demo"></p>
<script>
function run() {
var d = document.getElementById("idate").value;
document.getElementById("demo").innerHTML = d.slice(8, 10) + "/" + d.slice(5, 7) + "/" + d.slice(0, 4);
}
</script>
Source
https://www.w3schools.com/jsref/jsref_slice_string.asp

Shorter way to write this JavaScript date code

Hello I want to get today's date in JavaScript in the following format: dd/mm/YYYY
The following code does the job but surely there is a shorter way to write this?
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1;
var year = today.getFullYear();
var todaysDate = day + "/" + month + "/" + year;
Thanks in advance.
recommend a great js date/time lib: http://momentjs.com/
moment().format('D/M/YYYY'); //"10/2/2013"
if you need padding zeros:
moment().format('DD/MM/YYYY'); //"10/02/2013"
if you want write pure js, nothing much can do here, just cut off some variable.
var today = new Date;
//parenthesis around month is required.
var todaysDate = today.getDate() + '/' + (today.getMonth()+1) + '/' + today.getFullYear();
//"10/2/2013"
Of course.
var date = new Date();
var todaysDate = date.getDate() + "/" + date.getMonth()+1 + "/" + date.getFullYear();
Note that this will return values without leading zeros. You can add them using one extra function for convenience:
function checkTime(i){if(i<10){i="0" + i}return i}
var date = new Date();
var todaysDate = checkTime(date.getDate()) + "/" + checkTime(date.getMonth()+1) + "/" + date.getFullYear();
Although JavaScript provides a bunch of methods for getting and setting parts of a date object, it lacks a simple way to format dates and times according to a user-specified mask. Yours is quite simple enough.
You could use an external library, but the script size trade-off won't be optimal for just one simple operation.
A shorter version would be to combine the last 4 lines inline this way:
var today = new Date();
var todaysDate = today.getDate() + "/" + (today.getMonth()+1) + "/" + today.getFullYear();

Can I create a date object out of this type of string? in javascript?

Hello I have a XML file and a "created at" tag that stores the date and time like this
2012-09-15 02:08:46
I am trying to create a new Date object so I can easily print out the day month and year. But it doesn't like this format.
something like this
var theDate = new Date(Date.parse(storyDate));
console.log(theDate.getMonth());
theDate = theDate.getDate() + ", " + theDate.getMonth();
thanks
UPDATE: I can get it to work in Chrome but not Firefox.
UPDATE: Found the answer, thanks everybody. why the downvote? It turned out to be a reasonable question. I was missing a T.
var theDate = new Date(Date.parse(storyDate.replace(' ', 'T')));
The 'T' is required between the date and time.(at least in FireFox)
Valid DateTime formats
I would parse the date manually using regular expressions.
var dateStr = "2012-09-15 02:08:46"
var dateRegex = /^(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})$/
var dateParts = dateRegex.exec(dateStr)
var year = dateParts[1],
month = parseInt(dateParts[2], 10) - 1,
day = dateParts[3],
hour = dateParts[4],
minutes = dateParts[5],
seconds = dateParts[6];
var date = new Date(year, month, day, hour, minutes, seconds);
//
console.log(date.getMonth())
console.log(date.getDate() + ", " + date.getMonth());

Get String in YYYYMMDD format from JS date object?

I'm trying to use JS to turn a date object into a string in YYYYMMDD format. Is there an easier way than concatenating Date.getYear(), Date.getMonth(), and Date.getDay()?
Altered piece of code I often use:
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();
return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('');
};
var date = new Date();
date.yyyymmdd();
I didn't like adding to the prototype. An alternative would be:
var rightNow = new Date();
var res = rightNow.toISOString().slice(0,10).replace(/-/g,"");
<!-- Next line is for code snippet output only -->
document.body.innerHTML += res;
You can use the toISOString function :
var today = new Date();
today.toISOString().substring(0, 10);
It will give you a "yyyy-mm-dd" format.
Moment.js could be your friend
var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');
new Date('Jun 5 2016').
toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'}).
replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');
// => '2016-06-05'
If you don't need a pure JS solution, you can use jQuery UI to do the job like this :
$.datepicker.formatDate('yymmdd', new Date());
I usually don't like to import too much libraries. But jQuery UI is so useful, you will probably use it somewhere else in your project.
Visit http://api.jqueryui.com/datepicker/ for more examples
This is a single line of code that you can use to create a YYYY-MM-DD string of today's date.
var d = new Date().toISOString().slice(0,10);
I don't like modifying native objects, and I think multiplication is clearer than the string padding the accepted solution.
function yyyymmdd(dateIn) {
var yyyy = dateIn.getFullYear();
var mm = dateIn.getMonth() + 1; // getMonth() is zero-based
var dd = dateIn.getDate();
return String(10000 * yyyy + 100 * mm + dd); // Leading zeros for mm and dd
}
var today = new Date();
console.log(yyyymmdd(today));
Fiddle: http://jsfiddle.net/gbdarren/Ew7Y4/
In addition to o-o's answer I'd like to recommend separating logic operations from the return and put them as ternaries in the variables instead.
Also, use concat() to ensure safe concatenation of variables
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear();
var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
var dd = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
return "".concat(yyyy).concat(mm).concat(dd);
};
Date.prototype.yyyymmddhhmm = function() {
var yyyymmdd = this.yyyymmdd();
var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours();
var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes();
return "".concat(yyyymmdd).concat(hh).concat(min);
};
Date.prototype.yyyymmddhhmmss = function() {
var yyyymmddhhmm = this.yyyymmddhhmm();
var ss = this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds();
return "".concat(yyyymmddhhmm).concat(ss);
};
var d = new Date();
document.getElementById("a").innerHTML = d.yyyymmdd();
document.getElementById("b").innerHTML = d.yyyymmddhhmm();
document.getElementById("c").innerHTML = d.yyyymmddhhmmss();
<div>
yyyymmdd: <span id="a"></span>
</div>
<div>
yyyymmddhhmm: <span id="b"></span>
</div>
<div>
yyyymmddhhmmss: <span id="c"></span>
</div>
Local time:
var date = new Date();
date = date.toJSON().slice(0, 10);
UTC time:
var date = new Date().toISOString();
date = date.substring(0, 10);
date will print 2020-06-15 today as i write this.
toISOString() method returns the date with the ISO standard which is YYYY-MM-DDTHH:mm:ss.sssZ
The code takes the first 10 characters that we need for a YYYY-MM-DD format.
If you want format without '-' use:
var date = new Date();
date = date.toJSON().slice(0, 10).split`-`.join``;
In .join`` you can add space, dots or whatever you'd like.
Plain JS (ES5) solution without any possible date jump issues caused by Date.toISOString() printing in UTC:
var now = new Date();
var todayUTC = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
return todayUTC.toISOString().slice(0, 10).replace(/-/g, '');
This in response to #weberste's comment on #Pierre Guilbert's answer.
// UTC/GMT 0
document.write('UTC/GMT 0: ' + (new Date()).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812013509
// Client local time
document.write('<br/>Local time: ' + (new Date(Date.now()-(new Date()).getTimezoneOffset() * 60000)).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812113509
Another way is to use toLocaleDateString with a locale that has a big-endian date format standard, such as Sweden, Lithuania, Hungary, South Korea, ...:
date.toLocaleDateString('se')
To remove the delimiters (-) is just a matter of replacing the non-digits:
console.log( new Date().toLocaleDateString('se').replace(/\D/g, '') );
This does not have the potential error you can get with UTC date formats: the UTC date may be one day off compared to the date in the local time zone.
var someDate = new Date();
var dateFormated = someDate.toISOString().substr(0,10);
console.log(dateFormated);
dateformat is a very used package.
How to use:
Download and install dateformat from NPM. Require it in your module:
const dateFormat = require('dateformat');
and then just format your stuff:
const myYYYYmmddDate = dateformat(new Date(), 'yyyy-mm-dd');
Shortest
.toJSON().slice(0,10).split`-`.join``;
let d = new Date();
let s = d.toJSON().slice(0,10).split`-`.join``;
console.log(s);
Working from #o-o's answer this will give you back the string of the date according to a format string. You can easily add a 2 digit year regex for the year & milliseconds and the such if you need them.
Date.prototype.getFromFormat = function(format) {
var yyyy = this.getFullYear().toString();
format = format.replace(/yyyy/g, yyyy)
var mm = (this.getMonth()+1).toString();
format = format.replace(/mm/g, (mm[1]?mm:"0"+mm[0]));
var dd = this.getDate().toString();
format = format.replace(/dd/g, (dd[1]?dd:"0"+dd[0]));
var hh = this.getHours().toString();
format = format.replace(/hh/g, (hh[1]?hh:"0"+hh[0]));
var ii = this.getMinutes().toString();
format = format.replace(/ii/g, (ii[1]?ii:"0"+ii[0]));
var ss = this.getSeconds().toString();
format = format.replace(/ss/g, (ss[1]?ss:"0"+ss[0]));
return format;
};
d = new Date();
var date = d.getFromFormat('yyyy-mm-dd hh:ii:ss');
alert(date);
I don't know how efficient that is however, especially perf wise because it uses a lot of regex. It could probably use some work I do not master pure js.
NB: I've kept the predefined class definition but you might wanna put that in a function or a custom class as per best practices.
A little variation for the accepted answer:
function getDate_yyyymmdd() {
const date = new Date();
const yyyy = date.getFullYear();
const mm = String(date.getMonth() + 1).padStart(2,'0');
const dd = String(date.getDate()).padStart(2,'0');
return `${yyyy}${mm}${dd}`
}
console.log(getDate_yyyymmdd())
This guy here => http://blog.stevenlevithan.com/archives/date-time-format wrote a format() function for the Javascript's Date object, so it can be used with familiar literal formats.
If you need full featured Date formatting in your app's Javascript, use it. Otherwise if what you want to do is a one off, then concatenating getYear(), getMonth(), getDay() is probably easiest.
Little bit simplified version for the most popular answer in this thread https://stackoverflow.com/a/3067896/5437379 :
function toYYYYMMDD(d) {
var yyyy = d.getFullYear().toString();
var mm = (d.getMonth() + 101).toString().slice(-2);
var dd = (d.getDate() + 100).toString().slice(-2);
return yyyy + mm + dd;
}
You can simply use This one line code to get date in year
var date = new Date().getFullYear() + "-" + (parseInt(new Date().getMonth()) + 1) + "-" + new Date().getDate();
How about Day.js?
It's only 2KB, and you can also dayjs().format('YYYY-MM-DD').
https://github.com/iamkun/dayjs
Use padStart:
Date.prototype.yyyymmdd = function() {
return [
this.getFullYear(),
(this.getMonth()+1).toString().padStart(2, '0'), // getMonth() is zero-based
this.getDate().toString().padStart(2, '0')
].join('-');
};
This code is fix to Pierre Guilbert's answer:
(it works even after 10000 years)
YYYYMMDD=new Date().toISOString().slice(0,new Date().toISOString().indexOf("T")).replace(/-/g,"")
Answering another for Simplicity & readability.
Also, editing existing predefined class members with new methods is not encouraged:
function getDateInYYYYMMDD() {
let currentDate = new Date();
// year
let yyyy = '' + currentDate.getFullYear();
// month
let mm = ('0' + (currentDate.getMonth() + 1)); // prepend 0 // +1 is because Jan is 0
mm = mm.substr(mm.length - 2); // take last 2 chars
// day
let dd = ('0' + currentDate.getDate()); // prepend 0
dd = dd.substr(dd.length - 2); // take last 2 chars
return yyyy + "" + mm + "" + dd;
}
var currentDateYYYYMMDD = getDateInYYYYMMDD();
console.log('currentDateYYYYMMDD: ' + currentDateYYYYMMDD);
[day,,month,,year]= Intl.DateTimeFormat(undefined, { year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date()),year.value+month.value+day.value
or
new Date().toJSON().slice(0,10).replace(/\/|-/g,'')
From ES6 onwards you can use template strings to make it a little shorter:
var now = new Date();
var todayString = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}`;
This solution does not zero pad. Look to the other good answers to see how to do that.
I usually use the code below when I need to do this.
var date = new Date($.now());
var dateString = (date.getFullYear() + '-'
+ ('0' + (date.getMonth() + 1)).slice(-2)
+ '-' + ('0' + (date.getDate())).slice(-2));
console.log(dateString); //Will print "2015-09-18" when this comment was written
To explain, .slice(-2) gives us the last two characters of the string.
So no matter what, we can add "0" to the day or month, and just ask for the last two since those are always the two we want.
So if the MyDate.getMonth() returns 9, it will be:
("0" + "9") // Giving us "09"
so adding .slice(-2) on that gives us the last two characters which is:
("0" + "9").slice(-2)
"09"
But if date.getMonth() returns 10, it will be:
("0" + "10") // Giving us "010"
so adding .slice(-2) gives us the last two characters, or:
("0" + "10").slice(-2)
"10"
It seems that mootools provides Date().format(): https://mootools.net/more/docs/1.6.0/Types/Date
I'm not sure if it worth including just for this particular task though.
If you don't mind including an additional (but small) library, Sugar.js provides lots of nice functionality for working with dates in JavaScript.
To format a date, use the format function:
new Date().format("{yyyy}{MM}{dd}")

Categories

Resources