Adding days to a date - date getting converted to string - javascript

So I'm trying to add a certain number of days to a date, and I'm getting a strange issue:
var date = new Date();
var newdate = date.getDate() + $('#ddlDays option:selected').val();
date.setDate(newdate);
So if today is 09/29/2010, the Date is 29. But if a user selects "5" from ddlDays, it will assume I am adding strings together, adding 295 days to my date.
I was under the impression that javascript would assume they were integers? Does getDate() return a string instead of an integer?
How can I fix this?

If you just want to add the selected value to the day of the month (i.e. 29 + 5), then you need to parse the string value into an int:
var newdate = date.getDate() + parseInt( $('#ddlDays option:selected').val(), 10);
But if you actually want a new date, rather than an int, as your result, you can do something like this:
date.setDate( date.getDate() + parseInt( $('#ddlDays option:selected').val(), 10);

It is .val() that is returning a String. You can use .parseInt() to convert to a Number.
var newdate = date.getDate() +
(parseInt($('#ddlDays option:selected').val(), 10) || 0);
or
var newdate = date.getDate() + ~~$('#ddlDays option:selected').val();

No, the getDate() call doesn't return a string, but the val() call does.
You'll need to parse the string to an integer instead:
var newdate = date.getDate() + parseInt($('#ddlDays option:selected').val(), 10);

Surround your string value with parseInt. JavaScript will concatenate strings to numbers (see http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference for a thorough run through.)
This should do the trick:
var newdate = date.getDate() + parseInt($('#ddlDays option:selected').val());
or
var newdate = date.getDate() + parseInt($('#ddlDays option:selected').val(), 10);

adding days and converting it to a specific format are talked about in this question

Related

Have Javascript recognize YYYYmmdd in +5:00 Time Zone [duplicate]

I need my date to be in ccyymmdd format to add a day and pass over to a cobol application via xml. I also need to convert the new date with the added day to mm/dd/ccyy format to place into my slickgrid. My boss believes there has to be an easier way however, I can't seem to find one without using jquery or adding another library. Here is the code I am using;
// Roll date for status R1(rolled) today plus 1 day.
var rDate = (new Date()).toISOString().slice(0, 10).replace(/-/g, "");
(rDate++);
// Convert rDate back to useable date for updating ActionDate when rolling clt.
var uDate = (String(rDate)).replace(/(\d{4})(\d{2})(\d+)/, "$2/$3/$1");
So to preserve what you are doing (adding a day to the date), one solution is:
var rDate = new Date();
rDate.setDate(rDate.getDate() + 1);
var printDate = rDate.getFullYear()+('0'+(rDate.getMonth()+1)).slice(-2)+('0'+(rDate.getDate())).slice(-2);
The advantage here is that rDate is always a real Date object, so you don't have to convert it back - you can just use it for any output format you wish.
The Date object in JavaScript has getFullYear, getMonth, and day methods, which means you can do:
If you had a function pad(num, digits) which pads a number with leading zeroes, you can have:
var str = pad(date.getFullYear(), 4) + pad(1+ date.getMonth(), 2) + pad(date.getDate(), 2)
From Pad a number with leading zeros in JavaScript on stackoverflow, you can get a pad functio:
function pad(n, width) {
n += '';
return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n;
}
I don't think it's better, but another approach:
var d = new Date();
var datestr = [ d.getFullYear(), ('0' + (1+d.getMonth())).substr(-2), ("0" + d.getDate()).substr(-2) ].join('');
Two thing to clarify: getMonth() returns 0-based month number, hence the need to add 1. And the ("0" + number).substr(-2) is used to add leading zeroes to single digit numbers, because substr(-2) returns two last characters of a string.

How can I convert timestamp to date format yyyy-MM-dd'T'HH:mm:ssXXX?

I would like to know if there's a way to convert a timestamp to yyyy-MM-dd'T'HH:mm:ssXXX date format?
I can convert it to ISO using toISOString but it add Z at the end of the string.
Thank you.
var d = new Date();
var datestring = d.getDate() + "-" +
(d.getMonth() + 1) + "-" +
d.getFullYear() + "-T " +
d.getHours() + ":" +
d.getMinutes();
If you really do not want to use an external library like moment.js (which i would strongly recommend), as you stated in your comment, you will have to implement a function for that yourself, as regular javascript does not provide a function for this (as far as i know).
You can create an object of javascripts built-in Date class from a unix timestamp by using
var unixTimestamp = 1566394163;
//multiply with 1000 as Date expects milliseconds
var date = new Date(unixTimestamp * 1000);
Then you could build the output string yourself, by using something along this
var dateString = "";
dateString += date.getUTCFullYear()+"-";
dateString += date.getUTCMonth()+"-";
dateString += ...
On the other hand, if the Z at the end of the string is the only thing that bothers you about the format provided by toISOString() as a workaround you could use its output and remove the last character of it
var dateString = date.toISOString();
var newDateString = dateString.substr(0, dateString.length -1);
Please try using below code to convert timestamp to date format.
var date = new Date(timestamp*1000);
var year = date.getFullYear();
var month = months_arr[date.getMonth()];
var day = date.getDate();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
Display date time in any format you want.

Remove time part from date in js

let date = invoice.due_date;
console.log(date);
Output 2019-06-13 00:00:00
d = date.split(' ')[0]; //didnt work for me
How can I remove the time and only have the date.
I just added .toLocaleDateString
The toLocaleDateString() method returns a string with a language-sensitive representation of the date portion of the date. The locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function.
let date = new Date("2019-06-13T02:00:00Z").toLocaleDateString()
console.log(date)
Reference:
toLocaleDateString
Another Example:
If you want to have a ISO Date try this one:
date = new Date('2019-06-13T02:00:00Z');
year = date.getFullYear();
month = date.getMonth() + 1;
dt = date.getDate();
if (dt < 10) {
dt = '0' + dt;
}
if (month < 10) {
month = '0' + month;
}
console.log(year + '-' + month + '-' + dt);
let date = invoice.due_date;
console.log(date.getDate() + '-' + (date.getMonth()+1) + '-' + date.getFullYear());
You can try this way. Can create any format like dd-MM-yyyy or anything.
Recommendation: Use moment library for date formatting.
If you had a string, the split would work.
It is either not a string (e.g. null) or something else not a string.
Your console.log shows a date string so it is obviously a Date object.
To get the second part in ANY case (space or with a T between the date and time) you need to get the ISOString to be able to PERSISTENTLY get the correct output.
Any toLocaleString or similar is implementation and locale dependent
let date = invoice.due_date.toISOString()
Like this:
// Assuming a date object because your console log and the split that does not work
const invoice = {
due_date : new Date("2019-06-13 00:00:00") // EXAMPLE date
}
let date = invoice.due_date.toISOString();
console.log(date)
console.log(date.split(/[T| ]/)[0]); // take space or "T" as delimiter
You can convert the date string to a Date Object:
let dataObj = new Date(date)
and then format it as given in this link

JavaScript date conversion for a current date fetched from a device?

I am fetching current date from a device. It returns the date as 10-11-17
I want to convert it to 10-11-2017 using JavaScript.
I tried setUTCFullYear() and Moment.js but I didn't get any solution.
With moment you need to use the Parse method with a format string:
var d = moment('10-11-17', 'DD-MM-YY')
And the Format method:
console.log(d.format('DD-MM-YYYY'))
The docs have a lot of information.
try pure javascript method
let date = new Date('10-11-17');
date.toLocaleDateString();
you can just do this without moment.js.
format_date = function( date )
{
date = new Date( date );
var year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate();
if ( month.toString().length == 1 ) month = "0" + month;
if ( day.toString().length == 1 ) day = "0" + day;
return month + "-" + day + "-" + year;
}
var result = format_date( "10-11-17" );
console.log( result );
If all you want to do is convert a string 10-11-17 to 10-11-2017, then why not:
console.log('10-11-17'.replace(/(.*-)(.+)/,'$120$2'));
Which avoids all issues with parsing and formatting a date without using any libraries. It also doesn't care if the format is dd/mm/yy or mm/dd/yy.

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