How to generate date from current days to last days in Javascript? - javascript

I want to generate date as my below PHP code in Javascript But I don't know how to do.
$begin2 = new DateTime(date("Y-m-d", strtotime("-5 day")));
$interval2 = new DateInterval('P1D');
$end2 = new DateTime(date("Y-m-d", strtotime("+1 day")));
$daterange2 = new DatePeriod($begin2, $interval2, $end2);
foreach (array_reverse(iterator_to_array($daterange2)) as $val) {
echo $val->format("Ymd");
}
Output:
2015-12-04
2015-12-03
2015-12-02
2015-12-01
2015-11-30
2015-11-29
2015-11-28
2015-11-27
2015-11-26
2015-11-25

Edit
Wow, completely missed the point of the question!
Seems you want dates from today going backwards for a set number of days in ISO 8601 format. The Date constructor will create a date, and Date.prototype.toISOString will return an ISO 8601 date. It just needs the time part trimmed.
So a function to returns date strings for all the dates from today going back n days is:
function getDateRange(n) {
var d = new Date(),
dates = [];
while (n--) {
dates.push(d.toISOString().split('T')[0]);
d.setDate(d.getDate() - 1);
}
return dates;
}
// Example
document.write(getDateRange(10).join('<br>'));
Original answer
The only reliable way to parse date strings in javascript is to do it manually. A library can help, but a bespoke function isn't much work:
function parseYMD(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2]);
}
document.write(parseYMD('2015-12-04'))
This assumes the string is a valid date and will parse the string to a local Date, consistent with ECMAScript 2015 (and ISO 8601). If you need to also validate the string, a couple of extra lines are required.

Native "Date" will be enough for some date operations.
var myDate = new Date();
var dateLate = new Date();
var dateEarly = new Date();
dateLate.setDate(dateLate.getDate() + 10);
dateEarly.setDate(dateEarly.getDate() - 10);
myDate.setDate(dateLate.getDate());
while (myDate.getDate() != dateEarly.getDate()) {
myDate.setDate(myDate.getDate() - 1);
document.write(myDate.toLocaleDateString() + '<br>');
}
You can format the date in a different way.

Here's the code doing an iteration in reverse order for your given dates
var now = new Date();
var begin2 = new Date();
var end2 = new Date();
var year, month, day, datestr;
begin2.setDate(now.getDate() - 5);
end2.setDate(now.getDate() + 1);
var current = begin2;
var resulting_dates = [];
while (current <= end2) {
datestr = current.getFullYear() + '-' + ('0' + (current.getMonth() + 1)).slice(-2) + '-' + ('0' + current.getDate()).slice(-2);
resulting_dates.push(datestr);
current.setDate(current.getDate() + 1);
}
console.log(resulting_dates);

Related

How to format javascript date object?

i have 2 date fields which i want to compare their values. The problem is that i need the dates to be in dd/mm/yyyy format and as js date object. How can i change the date object format to receive dd/mm/yyyy and compare them with this format?
Here is what i've tried so far...
$('#date_customFrom').datepicker({
format: "dd/mm/yyyy"
});
$('#date_customTo').datepicker({
format: "dd/mm/yyyy"
});
$('.submit').on('click', function() {
var start_date = $("input[name='date_customFrom']").val().split("/");
var end_date = $("input[name='date_customTo']").val().split("/");
var new_date_start = new Date(start_date[2], start_date[1] - 1,
start_date[0]);
var new_date_end = new Date(end_date[2], end_date[1] - 1, end_date[0]);
console.log(new_date_start);
console.log(new_date_end);
});
fiddle
var dd = new_date_start.getDate();
var mm = new_date_start.getMonth() + 1;//January is 0!
var yyyy = new_date_start.getFullYear();
if (dd < 10) { dd = '0' + dd }
if (mm < 10) { mm = '0' + mm }
var res_START= dd + '/' + mm + '/' + yyyy;
console.log(res_START);
TRY THIS
You need use Moment.js
Here is doc
var momDt = moment('10.12.2016', 'DD/MM/YYYY');
You can compare Date objects with basic relational operators.
Make sure you are converting to numbers after splitting the string, using + or parseInt;
+(start_date[2])
Number(start_date[2])
parseInt(start_date[2], 10)
or map Number constructor after splitting
var start_date = $("input[name='date_customFrom']").val().split("/").map(Number);
new Date(start_date[2], start_date[1] - 1, start_date[0]);
Use <, <=, >, >= to compare now.
var start, end;
start = new Date(2016, 11, 5);
end = new Date(2016, 11, 4);
console.log(start, end, start < end)
start = new Date(2016, 11, 3);
end = new Date(2016, 11, 4);
console.log(start, end, start < end)
Fist of all, you do not need to cast the dates... the datepicker already can give you dates:
var start_date = $("#date_customFrom").datepicker('getDate');
var end_date = $("#date_customTo").datepicker('getDate');
Second, the correct format of the date is the date picker is
$('#date_customFrom').datepicker({
dateFormat: "dd/mm/yyyy"
});
Check this for the entire list of formats
http://api.jqueryui.com/datepicker/#utility-formatDate
Third, comparison is simply using relational comparison
if (start_date > end_date) {
}
You can create a format function:
function formatDate(date, search, replacement)
{
var target = date.toISOString().slice(0, 10);
return target.split(search).join(replacement);
}
and use it:
formatDate(new_date_start, "-", "/")
Here is your updated fiddle
But I agree with asdf_enel_hak's comment that moment.js would be a much better solution for you.
Update
I've just realized that the above will not take into consideration your timezone, so here is an updated function:
function formatDate(date, search, replacement)
{
var target = new Date(date);
target.setMinutes(date.getMinutes() - date.getTimezoneOffset());
target = target.toJSON().slice(0, 10);
return target.split(search).join(replacement);
}
And new fiddle

TypeError: *.getMonth is not a function

I'm trying to build a javascript function that will auto-fill 14 days of a calendar with dates leading up to the last date, which is picked by a datepicker. So far my code is:
function filldates() {
datepicked = document.getElementById("period-ending").value;
s = datepicked.split('/');
enddate = new Date(s[2], s[0], s[1]);
date1 = enddate.setDate(enddate.getDate()-14);
day1 = date1.getMonth() + 1;
month1 = date1.getDate();
var firstday = day1 + '/' + month1;
document.getElementById("date-1").value = firstday;
}
However the developer's console keeps telling me that date1.getMonth is not a function. I'm confused because all of the tutorials and examples I've been looking at are based around something like: "var today = new Date(); var month = today.getMonth() + 1;"
Is this an implementation problem?
The setDate() function mutates its context date. It does not return a new Date instance.
If you want to create a new date instance that's some number of days ahead of another one:
function daysAfter(d, days) {
var nd = new Date(d.getTime());
nd.setDate(d.getDate() + days);
return nd;
}
Then if you've got a date, you can create a date 14 days after it like this:
var someDate = ... whatever ... ;
var fourteenDaysAfter = daysAfter(someDate, 14);
You can then use the .getMonth() and .getDate() accessors to do whatever formatting you want. Keep in mind that months are numbered from zero in JavaScript.
edit for dates before a date just pass a negative number.

Get time difference in javascript ISO format

I have a datetime in ISO format i.e.
2012-06-26T01:00:44Z
I want to get the time difference from current time. How can I achieve this using javascript or javascript library Date.js or jquery
This will give you the difference in milliseconds, you can then format it as you want
var diff = new Date("2012-06-26T01:00:44Z") - new Date();
Try this:
var someDate = new Date("2012-06-26T01:00:44Z");
var now = new Date();
var one_day = 1000 * 60 * 60 * 24;
var diff = Math.ceil((someDate.getTime()-now .getTime())/(one_day))
alert(diff)
Example fiddle
You can obviously amend the one_day variable to get the difference in the unit you require.
I would suggest converting ISO format to something that works cross browser.
Try this,
var d = "2012-06-26T01:00:44Z";
var someDate = new Date(d.replace(/-/g,'/').replace('T',' ').replace('Z',''));
alert(someDate - new Date());
Edit:
I guess, you need pretty time
Try this awesome code
Edit 2:
You needed reverse, so try this instead
var old_date = new Date();
alert('Old date: ' + old_date.toGMTString())
var new_date = new Date(old_date.setMinutes(old_date.getMinutes() - 5));
alert('Date 5 minutes before: ' + new_date.toGMTString());
If you need timestamp,
alert(new_date.getTime());
in order to format date you can use this function to get the desire format of the date and you can easily change the position of day , month and year.
function convertFormat(inputDate)
var date = new Date(inputDate);
var day = date.getDate();
var month = date.getMonth()+1;
var year = date.getFullYear();
var fullYear = year + '/' + month + '/' + day
return fullYear;

Convert Returned String (YYYYMMDD) to Date

I have a string that contains 8 digits that represent a date. For example:
20120515
I'd like to compare it with today's date, created in this manner:
var currentDate = new Date();
How can I convert the "8 digit date string" to a suitable date format in order to compare it to currentDate?
Use the substring method and substring off 4 elements and assign it to your new date for the year. Then substring off two elements at a time and store the month and date accordingly.
var dateString = "20120515";
var year = dateString.substring(0,4);
var month = dateString.substring(4,6);
var day = dateString.substring(6,8);
var date = new Date(year, month-1, day);
var currentDate = new Date();
Now you can compare the two dates with the normal operators.
If you want a small date library you can use moment.js.
var a = moment("20120515", "YYYYMMDD");
// then use any of moment's manipulation or display functionality
a.format("MMM Do YYYY"); // May 15th 2012
a.fromNow(); // 14 hours ago
a.calendar(); // Today at 12:00 AM
To correctly handle the local time zone, it must explicitly summed to the calculated time
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
console.log(dateStringToDate("20211212"))
console.log(dateStringToDate("20211213"))
console.log(dateStringToDate("20211214"))
...some other "one-liner" ways to accomplish this:
(They take a value like dts='20020704'; and return date object [dt].)
var dt=new Date(dts.slice(0,4), (dts[4]+dts[5])-1, dts[6]+dts[7]);
...or...
var m=dts.match(/(....)(..)(..)/), dt=new Date(m[1],m[2]-1,m[3]);
...or...
var m=dts.match(/.{1,2}/g), dt=new Date(m[0]+m[1],m[2]-1,m[3]);
The last one's shortest, but the first is probably most efficient, since it doesn't use regex (but that's irrelevant, unless you're processing LOTS of data using this). I like the middle one best since it's easy to see what's happening.

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