Converting date format from php/html into js [duplicate] - javascript

This question already has answers here:
Calculate last day of month
(25 answers)
Closed 3 years ago.
As title says, I'm stuck on finding a way to get the first and last date of the current month with JavaScript or jQuery, and format it as:
For example, for November it should be :
var firstdate = '11/01/2012';
var lastdate = '11/30/2012';

Very simple, no library required:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
or you might prefer:
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
EDIT
Some browsers will treat two digit years as being in the 20th century, so that:
new Date(14, 0, 1);
gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:
var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14

I fixed it with Datejs
This is alerting the first day:
var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);
This is for the last day:
var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);

Related

I am Working on Javascript Dates, i am stuck with adding 7 days to a date [duplicate]

This question already has answers here:
How to add days to Date?
(56 answers)
Closed 2 years ago.
var date = new Date();
var first_date = new Date(date); //Make a copy of the date we want the first and last days from
first_date.setUTCDate(1); //Set the day as the first of the month
var firstDay = first_date.toJSON().substring(0, 10);
console.log(firstDay)
I am Working on Javascript Dates, i am stuck with adding 7 days to this date
Thanks in advance
var date = new Date();
var first_date = new Date(date); //Make a copy of the date we want the first and last days from
first_date.setUTCDate(1); //Set the day as the first of the month
var firstDay = first_date.toJSON().substring(0, 10);
var resultDate = new Date();
resultDate.setDate(first_date.getDate() + 7);
var resultDay = resultDate.toJSON().substring(0, 10);
console.log("First day: " + firstDay)
console.log("7 days from specific day: " + resultDay)

Getting 2020-02-29T00:00:00.000Z for March using momentjs or Date()

I'm trying to get start and end of the current month but for march it is giving me the start date as
2020-02-29T00:00:00.000Z
Using momentjs
var firstDay = new moment().startOf('month').utcOffset(0);
firstDay.set({hour:0,minute:0,second:0,millisecond:0});
var lastDay = new moment().endOf('month').utcOffset(0);
lastDay.set({hour:23,minute:59,second:59,millisecond:0})
Using Date()
var date = new Date(),
y = date.getFullYear(),
m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 1);
How to solve this?
Try startOf / endOf followed by utcOffset()
Note: startOf - set to the first of this month, 12:00 am
var firstDay = new moment('2020-02-29T00:00:00.000Z').utcOffset(0).startOf('month');
console.log(firstDay.format())
var lastDay = new moment('2020-02-29T00:00:00.000Z').utcOffset(0).endOf('month');
console.log(lastDay.format())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
For march it should be like this using utcOffset(0) then call the function startof():
var startDay = new moment().utcOffset(0).startOf('month').format();
var endDay = new moment().utcOffset(0).endOf('month').format();
console.log(startDay);
console.log(endDay);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
var firstDay = new moment('2020-02-29T00:00:00.000Z').utcOffset(0).startOf('month');
console.log(firstDay.format())
var lastDay = new moment('2020-02-29T00:00:00.000Z').utcOffset(0).endOf('month');
console.log(lastDay.format())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

javascript return wrong first date and last dates

I found this code can be used to find the first date and the last date of a current month.
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
Today is 11/1/2018
I used this piece of code for a calendar I am developing for one of my projects. Even though it should return first day of the month as 2018-01-01T18:30:00.000Z it returns the first day as 2017-12-31T18:30:00.000Z and the last date as 2018-01-30T18:30:00.000Z.
But there are 31 days in January. So what is wrong with this code?
I found the code from a stackoverflow question
There is nothing wrong with the code. The inconsistency you see here is actually the timezone difference. Your plugin is printing the date in ISO string. To get this string in your own locale, use toLocaleString() on the date objects:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
console.log(firstDay.toLocaleString());
console.log(lastDay.toLocaleString());

How to get the first date of the current month in Node.js?

I'm trying to get the first and last date of the current month using Node.js.
Following code is working perfectly in browser (Chrome):
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
console.log(firstDay);
console.log(lastDay);
But it is showing a different result in Node.js. How can I fix it?
Changing the native Date object in the accepted answer is bad practice; don't do that ( https://stackoverflow.com/a/8859896/3929494 )
You should use moment.js to give you a consistent environment for handling dates in JavaScript between node.js and all browsers - see it as an abstraction layer. http://momentjs.com/ - it's quite easy to use.
A very similar example is here: https://stackoverflow.com/a/26131085/3929494
You can try it on-line at https://tonicdev.com/jadaradix/momentjs
The browser output is showing the date in the current time zone, node.js is showing the date GMT / Zulu time zone.
(Edit: Code added). Something like this
var offset = (new Date().getTimezoneOffset() / 60) * -1;
var d = new Date();
var tmpDate = new Date(d.getTime()+offset);
var y = tmpDate.getFullYear();
var m = tmpDate.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
console.log(tmpDate.toString());
console.log(firstDay.toString());
console.log(lastDay.toString());
Create a new file dates.js and add the following code. To execute this code run the command node dates.js from your terminal. You can use this function to get first and last days dates in a given month. I tested this on node 12
const getDays = () => {
const date = new Date();
const year = date.getFullYear();
let month = date.getMonth() + 1;
let f = new Date(year, month, 1).getDate();
let l = new Date(year, month, 0).getDate();
f = f < 10 ? '0'+f : f;
l = l < 10 ? '0'+l : l;
month = month < 10 ? '0'+month : month;
const firstDay = new Date(`${year}-${month}-${f}`);
const lastDay = new Date(`${year}-${month}-${l}`);
console.log({
"firstDay": firstDay,
"lastDay": lastDay
});
};
getDays();
Look at the code
<html>
<head>
<title>Please Rate if it helps</title>
<script>
Date.prototype.getMonthStartEnd = function (start) {
var StartDate = new Date(this.getFullYear(), this.getMonth(), 1);
var EndDate = new Date(this.getFullYear(), this.getMonth() + 1, 0);
return [StartDate, EndDate];
}
window.onload = function () {
document.write(new Date().getMonthStartEnd());
}
</script>
</head>
<body>
</body>
</html>

javascript date of last day of previous month

Let's say I have 3 variables like this:
var Month = 8; // in reality, it's a parameter provided by some user input
var Year = 2011; // same here
var FirstDay = new Date(Year, Month, 1);
Now I want to have the value of the day before the first day of the month in a variable. I'm doing this:
var LastDayPrevMonth = (FirstDay.getDate() - 1);
It's not working as planned. What the right of doing it?
Thanks.
var LastDayPrevMonth = new Date(Year, Month, 0).getDate();
var LastDayPrevMonth = new Date(FirstDay);
LastDayPrevMonth.setHours(FirstDay.getHours()-24);
var FirstDay = new Date(Year, Month, 1);
var lastMonth = new Date(FirstDay);
lastMonth.setDate(-1);
alert(lastMonth);
And remember that 8 is Sept, not Aug in JavaScript. :)
If you need to calculate this based on today's date ( you want the last day of last month ), the following should help.
If you only care about the month/day/year, this is the simplest and fastest that I can think of:
var d = new Date(); d.setDate(0);
console.log(d);
If you want midnight of last day of the previous month, then:
var d = new Date(); d.setDate(0); d.setHours(0,0,0,0);
console.log(d);
If you want to know the last day of the previous month, based on provided year/month:
var year = 2016, month = 11;
var d = new Date(year, (month - 1)); d.setDate(0); d.setHours(0,0,0,0);
console.log(d);
After running any of the above, to get the YYYY-M-D format:
var str = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
console.log(str);
To see additional methods available, and to see what they do, you can read the docs.
Create a new Date object and pass it the other date coerced to the number of milliseconds since the Unix epoch and then minus a whole day (in milliseconds).
var LastDayPrevMonth = new Date(FirstDay - 864e5);
Example:
var Month = 8; // in reality, it's a parameter provided by some user input
var Year = 2011; // same here
var FirstDay = new Date(Year, Month, 1);
var LastDayPrevMonth = new Date(FirstDay - 864e5);
document.body.innerHTML = LastDayPrevMonth;

Categories