Can you help me with this problem? I tried to make a function that receives a parameter of type Date e.g. 12.11.2020. I want it to return the previous day.
function getPreviousDay(d) {
var dateObj = new Date(d);
var previousDay = dateObj.setDate(dateObj.getDate() - 1);
return previousDay;
}
console.log(getPreviousDay(new Date())); //1606809601830
But as you see, the function returns: 1606809601830, I don't know why.
Thank you, guys!
A simple ES6 one-liner would be :
const getPreviousDay = d => d.setDate(d.getDate() - 1) && d
console.log(getPreviousDay(new Date()));
This function changes the day of the Date object you pass it, and returns it. No need to create an intermediary one.
Typescript version (with type checking, to make sure you always pass it a Date object, and not a string) :
const getPreviousDay = (d:Date): Date => d.setDate(d.getDate() - 1) && d
You don't want to return the result of Date.prototype.setDate() which is the date in milliseconds, you want to return the mutated dateObj
function getPreviousDay(d) {
var dateObj = new Date(d);
dateObj.setDate(dateObj.getDate() - 1);
return dateObj ;
}
console.log(getPreviousDay(new Date()));
This code return like this yesterday date(1.12.2020).
function getPreviousDay(d) {
var dateObj = new Date(d);
dateObj.setDate(dateObj.getDate()-1);
return dateObj.getDate() + '.' + (dateObj.getMonth()+1) + '.' + dateObj.getFullYear();
}
console.log(getPreviousDay(new Date()));
Related
I wrote code for getting the coming Saturday. So I wrote like this and the result is 2020-03-07T04:00:48.306Z. I found the dateT~~. I just only need the date. I can use the split method, but I don't wanna use this. is there any other way?
function getSaturday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate()+5 - day + (day == 5 ? 7:1);
console.log(diff);
return new Date(d.setDate(diff));
}
Try with substr,
function getSaturday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate()+5 - day + (day == 5 ? 7:1);
console.log(diff);
return new Date(d.setDate(diff)).toISOString.substr(0,10);
}
Your getSaturday function returns a new Date object (which is the Saturday).
The simplest way is to use split to get the date string back
const d = getSaturday(...)
d.toISOString().split("T")[0]
But since you don't want to use split. You may want to use moment: a very popular and lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates.
And then you can rewrite your function like this:
function getSaturday(d) {
return moment(d).day("Saturday").format("YYYY-MM-DD")
}
console.log(getSaturday(new Date()))
<script src="https://momentjs.com/downloads/moment.js"></script>
function getSaturday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate()+5 - day + (day == 5 ? 7:1);
console.log(diff);
return new Date(d.setDate(diff));
}
function dateSaturday(d) {
var ds = [
d.getFullYear(),
((d.getMonth()+1) < 10) ? `0${(d.getMonth()+1)}` : (d.getMonth() +1).toString(),
(d.getDate() < 10) ? `0${d.getDate()}` : d.getDate().toString()
];
return ds.join("-")
}
console.log(dateSaturday(getSaturday("2020-03-04")));
Date
I have try to get dates list between two date using JavaScript (I have already achieved in GMT).
Example:
fromDate - 2019-08-27
toDate - 2019-08-30
Date list
[2019-08-27, 2019-08-28, 2019-08-29, 2019-08-30]
I have already got this array using this following JavaScript
if(result.data.closurPeriods.length > 0) {
result.data.closurPeriods.forEach(closure => {
var start = closure.fromDate, //closure.fromDate = 2019-08-27
end = new Date(closure.toDate), //closure.toDate = 2019-08-30
currentDate = new Date(start);
while (currentDate <= end) {
this.closurPeriods.push(this.datePipe.transform(new Date(currentDate), 'yyyy-MM-dd'));
currentDate.setDate(currentDate.getDate() + 1);
}
});
}
The above JavaScript is working for only GTM and localtime(India). When I try to run this script in USA the date list array like this
[2019-08-28, 2019-08-28, 2019-08-29]
Because of UTC not accept this script.
My question is how to solve this above script in UTC
2019-08-27 is parsed as UTC, but getDate and setDate are local. The USA is west of Greenwich, so new Date('2019-08-27') produces a local date for 2019-08-26, adding a day makes it 2019-08-27.
The same thing will happen for any timezone that has a negative offset.
A simple fix is to use all UTC, e.g.:
function fillRange(start, end) {
let result = [start];
let a = new Date(start);
let b = new Date(end);
while (a < b) {
a.setUTCDate(a.getUTCDate() + 1);
result.push(a.toISOString().substr(0,10));
}
return result;
}
let from = '2019-08-27';
let to = '2019-08-30';
console.log(fillRange(from, to));
However, I'd advise explicitly parsing the date and not to use the built–in parser. A simple parse function is 2 or 3 lines of code, or you can use one of many parsing and formatting libraries.
Finally i got the solutions
var start = new Date(closure.fromDate); // 2019-07-27
var end = new Date(closure.toDate); // 2019-07-31
var currentDate = start;
while (currentDate <= end) {
//this.closurPeriods.push(this.datePipe.transform(new Date(currentDate), 'yyyy-MM-dd'));
var date = new Date(currentDate);
var datewithouttimezone = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
this.closurPeriods.push(this.datePipe.transform(new Date(datewithouttimezone), 'yyyy-MM-dd'));
currentDate.setDate(currentDate.getDate() + 1);
}
Or
var start = new Date(closure.fromDate); // 2019-07-27
var end = new Date(closure.toDate); // 2019-07-31
var currentDate = start;
while (start < end) {
start.setUTCDate(start.getUTCDate() + 1);
this.closurPeriods.push(start.toISOString().substr(0, 10));
}
I'm trying to parse a date to mm/dd/yyyy format.
My function:
function formatDate(value) {
// value = '2016-07-05T00:00:00-04:00'
var dt = new Date();
dt = Date.parse(value); // dt = 1467691200000
return dt.getMonth() + 1 + "/" + dt.getDate() + "/" + dt.getFullYear();
}
I'm getting this error:
dt.getMonth is not a function
It seems that dt isn't a valid date so I can't access getMonth() method. Just not sure what I need in order to get this to work.
Date.parse() doesn't returns an object type Date, you can check it: console.log(typeof dt);.
So, you can do it using toLocaleDateString method.
Here's is the snippet working:
function formatDate(value) {
var dt = new Date(value);
dt.setMonth(dt.getMonth() + 1);
console.log(dt.toLocaleDateString());
}
var dates = ['2016-05-04T00:00:00-04:00', '2013-07-05T00:00:00-02:00', '2015-04-06T00:00:00-01:00'];
for (var i = 0; i < dates.length; i++) {
formatDate(dates[i]);
}
Note: toLocaleDateString method uses your locale conventions, in other words, it can returns in another format for another user.
I hope it helps.
Try to pass value as a parameter when creating the Date, instead of separately calling the parse function.
function formatDate(value) {
var dt = new Date(value);
return dt.getMonth() + 1 + "/" + dt.getDate() + "/" + dt.getFullYear();
}
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);
How to get the date trimmed of exactly in the format of (dd/mm/yyyy) in the following implementation of my code using JavaScript
<script type="text/javascript" language="javascript">
function disptextbox() {
var d = new Date();
var x = document.getElementById("ddlweeklist").value;
switch (x)
{
case "1":
document.getElementById("txtstart").value = d.toDateString();
document.getElementById("Txtend").value = d.toDateString();
break;
case "2":
var firstday = new Date(d.setDate(d.getDate() - d.getDay()));
var lastday = new Date(d.setDate(d.getDate() - d.getDay() + 6));
document.getElementById("txtstart").value= firstday.toDateString();
document.getElementById("Txtend").value = lastday.toDateString();
break;
case "3":
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
document.getElementById("txtstart").value = firstDay.toDateString();
document.getElementById("Txtend").value = lastDay.toDateString();
break;
case "4":
var firstd = new Date(d.getFullYear(), 0, 1);
var lastd = new Date(d.getFullYear(), 11, 31);
document.getElementById("txtstart").value = firstd.toDateString();
document.getElementById("Txtend").value = lastd.toDateString();
break;
}
}
</script>
in this code of implementation I want the date format to be in dd/mm/yyyy format ...I will be glad if any one help me over this this function call occurs on the drop down change especially...I am ok with functionality of the code but not comfortable in handling with DATE FUNCTIONS...
so please suggest me where I can get good examples for implementing date functions...in javascript
You can do this if you want dd/mm/yyyy format date:
new Date().toISOString().substr(0,10).replace(/(\d{4})-(\d{2})-(\d{2})/g,"$3/$2/$1");
I've written a couple of prototypes for dates than you may find useful:
Date.prototype.dateStr=function(split){
split=split===undefined?"-":split;
var output=parseInt(parseInt(this.getMonth())+1).toString().toLength(2);
output+=split;
output+=this.getDate().toString().toLength(2);
output+=split;
output+=this.getFullYear().toString().toLength(4);
return output;
}
Date.prototype.FOM=function(){
return new Date(this.getFullYear(),this.getMonth(),1);
}
String.prototype.toLength=function(len,fill){
fill=fill===undefined?"0":fill;
var outStr=this.toString();
while (outStr.length<parseInt(len)){
outStr=fill+outStr;
}
return outStr;
}
Technically, the 3rd one is a string prototype, but whatever. new Date().FOM() will give you a javascript date object for the first day of whatever month you pass it. new Date().dateStr("/") will give you a string - mm/dd/yyyy format - with separators as whatever you pass it, default "-".
That last one will take a string and make it a certain length by prepending the 'fill' - default '0'.
You could try with this function:
function toDateString(mydate) {
var day = mydate.getDate();
var month = mydate.getMonth();
day = day < 10 ? '0'+day : day;
month = month < 10 ? '0'+month : month;
return day + '/' + month + '/' + mydate.getYear();
}
You could then use it this way:
alert(toDateString(firstday)); // I'm using alert just for demonstration purposes
Here is a DEMO you could fiddle with.
EDITED: Learning from #Helpful's answer below, my above function could be used as a prototype to better fit the way you wrote up your code like this:
Date.prototype.toDateString=function() {
var day = this.getDate();
var month = this.getMonth();
day = day < 10 ? '0'+day : day;
month = month < 10 ? '0'+month : month;
return day + '/' + month + '/' + this.getYear();
}
so you could call it this way:
alert(thedate.toDateString()); // This is how you used it, if I understood it well.
Here is a DEMO of that.
Pass any data format
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
}
hope this will help you sure.....