Related
I've created this script to calculate the date for 10 days in advance in the format of dd/mm/yyyy:
var MyDate = new Date();
var MyDateString = new Date();
MyDate.setDate(MyDate.getDate()+10);
MyDateString = MyDate.getDate() + '/' + (MyDate.getMonth()+1) + '/' + MyDate.getFullYear();
I need to have the date appear with leading zeroes on the day and month component by way of adding these rules to the script. I can't seem to get it to work.
if (MyDate.getMonth < 10)getMonth = '0' + getMonth;
and
if (MyDate.getDate <10)get.Date = '0' + getDate;
If someone could show me where to insert these into the script I would be really appreciative.
Try this: http://jsfiddle.net/xA5B7/
var MyDate = new Date();
var MyDateString;
MyDate.setDate(MyDate.getDate() + 20);
MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'
+ ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'
+ MyDate.getFullYear();
EDIT:
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 MyDate.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"
The modern way
The new modern way to do this is to use toLocaleDateString, because it allows you not only to format a date with proper localization, but even to pass format options to achieve the desired result:
const date = new Date(2018, 2, 1)
const result = date.toLocaleDateString("en-GB", { // you can use undefined as first argument
year: "numeric",
month: "2-digit",
day: "2-digit",
})
console.log(result) // outputs “01/03/2018”
Or using a Temporal object (still in proposal, caniuse):
const date = new Temporal.PlainDate(2018, 3, 1) // also works with zoned date
const result = date.toLocaleString("en-GB", { // you can use undefined as first argument
year: "numeric",
month: "2-digit",
day: "2-digit",
})
console.log(result) // outputs “01/03/2018”
When you use undefined as the first argument it will detect the browser language, instead. Alternatively, you can use 2-digit on the year option, too.
Performance
If you plan to format a lot of dates, you should consider using Intl.DateTimeFormat instead:
const formatter = new Intl.DateTimeFormat("en-GB", { // <- re-use me
year: "numeric",
month: "2-digit",
day: "2-digit",
})
const date = new Date(2018, 2, 1) // can also be a Temporal object
const result = formatter.format(date)
console.log(result) // outputs “01/03/2018”
The formatter is compatible with Date and Temporal objects.
Historical dates
Unlike in the Temporal constructor years between 0 and 99 will be interpreted as 20th century years on the Date constructor. To prevent this, initialize the date like so:
const date = new Date()
date.setFullYear(18, 2, 1) // the year is A.D. 18
This is not required for Temporal objects, but years below 1000 will not contain leading zeros in all cases, because the formatter (that is shared for the Date and Temporal API) does not support 4-digit formatting at all. In this case you have to do manual formatting (see below).
For the ISO 8601 format
If you want to get your date in the YYYY-MM-DD format (ISO 8601), the solution looks different:
const date = new Date(Date.UTC(2018, 2, 1))
const result = date.toISOString().split('T')[0]
console.log(result) // outputs “2018-03-01”
Your input date should be in the UTC format or toISOString() will fix that for you. This is done by using Date.UTC as shown above.
Historical dates for the ISO 8601 format
Unlike in the Temporal constructor years between 0 and 99 will be interpreted as 20th century years on the Date constructor. To prevent this, initialize the date like so to be used for the ISO 8601 format:
const date = new Date()
date.setUTCFullYear(18, 2, 1) // the year is A.D. 18
Note that the ISO format for Temporal objects with dates before the year 1000 or after the year 9999 will have a different formatting compared to the legacy Date API. It is recommend to fallback to custom formatting to enforce 4 digit years in all circumstances.
Custom 4-digit formatting on the year
Sadly, the formatter doesn't support leading zeros on the year. There is no 4-digit option. This will remain for Temporal objects as well, because they do share the same formatter.
Fortunately, the ISO format of the Date API will always display at least 4 digits on the year, although Temporal objects do not. So at least for the Date API you can format historical dates before the year 1000 with leading zeros by falling back to a manual formatting approach using part of the ISO 8601 format method:
const date = new Date()
date.setUTCFullYear(18, 2, 1)
const ymd = date.toISOString().split('T')[0].split('-')
const result = `${ymd[2]}/${ymd[1]}/${ymd[0]}`
console.log(result) // outputs “01/03/0018”
For a Temporal object a different route is necessary, since the ISOYearString will be formatted differently for dates before the year 1000 and after the year 9999 as mentioned before:
const date = new Temporal.PlainDate(2018, 3, 1) // also works with zoned date
const zeroPad = (n, digits) => n.toString().padStart(digits, '0');
const result = `${zeroPad(date.day, 2)}/${zeroPad(date.month, 2)}/${zeroPad(date.year, 4)}`;
console.log(result) // outputs “01/03/0018”
Miscellaneous
For the Date and Temporal API there is also toLocaleTimeString, that allows you to localize and format the time of a date.
Here is an example from the Date object docs on the Mozilla Developer Network using a custom "pad" function, without having to extend Javascript's Number prototype. The handy function they give as an example is
function pad(n){return n<10 ? '0'+n : n}
And below is it being used in context.
/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var d = new Date();
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z
For you people from the future (ECMAScript 2017 and beyond)
Solution
"use strict"
const today = new Date()
const year = today.getFullYear()
const month = `${today.getMonth() + 1}`.padStart(2, "0")
const day = `${today.getDate()}`.padStart(2, "0")
const stringDate = [day, month, year].join("/") // 13/12/2017
Explaination
the String.prototype.padStart(targetLength[, padString]) adds as many as possible padString in the String.prototype target so that the new length of the target is targetLength.
Example
"use strict"
let month = "9"
month = month.padStart(2, "0") // "09"
let byte = "00000100"
byte = byte.padStart(8, "0") // "00000100"
You can define a "str_pad" function (as in php):
function str_pad(n) {
return String("00" + n).slice(-2);
}
I found the shorterst way to do this:
MyDateString.replace(/(^|\D)(\d)(?!\d)/g, '$10$2');
will add leading zeros to all lonely, single digits
Number.prototype.padZero= function(len){
var s= String(this), c= '0';
len= len || 2;
while(s.length < len) s= c + s;
return s;
}
//in use:
(function(){
var myDate= new Date(), myDateString;
myDate.setDate(myDate.getDate()+10);
myDateString= [myDate.getDate().padZero(),
(myDate.getMonth()+1).padZero(),
myDate.getFullYear()].join('/');
alert(myDateString);
})()
/* value: (String)
09/09/2010
*/
Nowadays you can also utilize String.prototype.padStart to reach the goal in quick and easy way
String(new Date().getMonth() + 1).padStart(2, '0')
The availability can be assessed at caniuse
var date = new Date()
var year = date.getFullYear()
var month = String(date.getMonth() + 1).padStart(2, '0')
var day = String(date.getDate()).padStart(2, '0')
console.log('%s/%s/%s', month, day, year)
Check
var date = new Date('7/4/2021')
var year = date.getFullYear()
var month = String(date.getMonth() + 1).padStart(2, '0')
var day = String(date.getDate()).padStart(2, '0')
/**
* Expected output: 07/04/2021
*/
console.log('%s/%s/%s', month, day, year)
Polyfill for old browsers
String.prototype.padStart || Object.defineProperty(String.prototype, 'padStart', {
configurable : true,
writable : true,
value : function (targetLength, padString) {
'use strict'
/**
* String.prototype.padStart polyfill
* https://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date
*/
targetLength = targetLength | 0
padString = arguments.length > 1 ? String(padString) : ' '
if (this.length < targetLength && padString.length) {
targetLength = targetLength - this.length
while (padString.length < targetLength) {
padString += padString
}
return padString.slice(0, targetLength) + this
} else {
return this
}
}
})
var MyDate = new Date();
var MyDateString = '';
MyDate.setDate(MyDate.getDate());
var tempoMonth = (MyDate.getMonth()+1);
var tempoDate = (MyDate.getDate());
if (tempoMonth < 10) tempoMonth = '0' + tempoMonth;
if (tempoDate < 10) tempoDate = '0' + tempoDate;
MyDateString = tempoDate + '/' + tempoMonth + '/' + MyDate.getFullYear();
There is another approach to solve this problem, using slice in JavaScript.
var d = new Date();
var datestring = d.getFullYear() + "-" + ("0"+(d.getMonth()+1)).slice(-2) +"-"+("0" + d.getDate()).slice(-2);
the datestring return date with format as you expect: 2019-09-01
another approach is using dateformat library: https://github.com/felixge/node-dateformat
You could use ternary operator to format the date like an "if" statement.
For example:
var MyDate = new Date();
MyDate.setDate(MyDate.getDate()+10);
var MyDateString = (MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate()) + '/' + ((d.getMonth()+1) < 10 ? '0' + (d.getMonth()+1) : (d.getMonth()+1)) + '/' + MyDate.getFullYear();
So
(MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate())
would be similar to an if statement, where if the getDate() returns a value less than 10, then return a '0' + the Date, or else return the date if greater than 10 (since we do not need to add the leading 0). Same for the month.
Edit:
Forgot that getMonth starts with 0, so added the +1 to account for it. Of course you could also just say d.getMonth() < 9 :, but I figured using the +1 would help make it easier to understand.
function formatDate(jsDate){
// add leading zeroes to jsDate when days or months are < 10..
// i.e.
// formatDate(new Date("1/3/2013"));
// returns
// "01/03/2103"
////////////////////
return (jsDate.getDate()<10?("0"+jsDate.getDate()):jsDate.getDate()) + "/" +
((jsDate.getMonth()+1)<10?("0"+(jsDate.getMonth()+1)):(jsDate.getMonth()+1)) + "/" +
jsDate.getFullYear();
}
You can provide options as a parameter to format date. First parameter is for locale which you might not need and second is for options.
For more info visit
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
var date = new Date(Date.UTC(2012, 1, 1, 3, 0, 0));
var options = { year: 'numeric', month: '2-digit', day: '2-digit' };
console.log(date.toLocaleDateString(undefined,options));
I wrapped the correct answer of this question in a function that can add multiple leading zero's but defaults to adding 1 zero.
function zeroFill(nr, depth){
depth = (depth === undefined)? 1 : depth;
var zero = "0";
for (var i = 0; i < depth; ++i) {
zero += "0";
}
return (zero + nr).slice(-(depth + 1));
}
for working with numbers only and not more than 2 digits, this is also an approach:
function zeroFill(i) {
return (i < 10 ? '0' : '') + i
}
Another option, using a built-in function to do the padding (but resulting in quite long code!):
myDateString = myDate.getDate().toLocaleString('en-US', {minimumIntegerDigits: 2})
+ '/' + (myDate.getMonth()+1).toLocaleString('en-US', {minimumIntegerDigits: 2})
+ '/' + myDate.getFullYear();
// '12/06/2017'
And another, manipulating strings with regular expressions:
var myDateString = myDate.toISOString().replace(/T.*/, '').replace(/-/g, '/');
// '2017/06/12'
But be aware that one will show the year at the start and the day at the end.
Adding on to #modiX answer, this is what works...DO NOT LEAVE THAT as empty
today.toLocaleDateString("default", {year: "numeric", month: "2-digit", day: "2-digit"})
Here is very simple example how you can handle this situation.
var mydate = new Date();
var month = (mydate.getMonth().toString().length < 2 ? "0"+mydate.getMonth().toString() :mydate.getMonth());
var date = (mydate.getDate().toString().length < 2 ? "0"+mydate.getDate().toString() :mydate.getDate());
var year = mydate.getFullYear();
console.log("Format Y-m-d : ",year+"-"+month+"-" + date);
console.log("Format Y/m/d : ",year+"/"+month+"/" + date);
I think this solution is easier and can be easily remembered:
var MyDate = new Date();
var day = MyDate.getDate() + 10; // 10 days in advance
var month = MyDate.getMonth() + 1; // since months start from 0 we should add 1 to it
var year = MyDate.getFullYear();
day = checkDate(day);
month = checkDate(month);
function checkDate(i){
if(i < 10){
i = '0' + i;
}
return i;
}
console.log(`${month}/${day}/${year}`);
What I would do, is create my own custom Date helper that looks like this :
var DateHelper = {
addDays : function(aDate, numberOfDays) {
aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays
return aDate; // Return the date
},
format : function format(date) {
return [
("0" + date.getDate()).slice(-2), // Get day and pad it with zeroes
("0" + (date.getMonth()+1)).slice(-2), // Get month and pad it with zeroes
date.getFullYear() // Get full year
].join('/'); // Glue the pieces together
}
}
// With this helper, you can now just use one line of readable code to :
// ---------------------------------------------------------------------
// 1. Get the current date
// 2. Add 20 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));
(see also this Fiddle)
As #John Henckel suggests, starting using the toISOString() method makes things easier
const dateString = new Date().toISOString().split('-');
const year = dateString[0];
const month = dateString[1];
const day = dateString[2].split('T')[0];
console.log(`${year}-${month}-${day}`);
try this for a basic function, no libraries required
Date.prototype.CustomformatDate = function() {
var tmp = new Date(this.valueOf());
var mm = tmp.getMonth() + 1;
if (mm < 10) mm = "0" + mm;
var dd = tmp.getDate();
if (dd < 10) dd = "0" + dd;
return mm + "/" + dd + "/" + tmp.getFullYear();
};
You could simply use :
const d = new Date();
const day = `0${d.getDate()}`.slice(-2);
So a function could be created like :
AddZero(val){
// adding 0 if the value is a single digit
return `0${val}`.slice(-2);
}
Your new code :
var MyDate = new Date();
var MyDateString = new Date();
MyDate.setDate(MyDate.getDate()+10);
MyDateString = AddZero(MyDate.getDate()) + '/' + AddZero(MyDate.getMonth() + 1) + '/' + MyDate.getFullYear();
toISOString can get leading 0
const currentdate = new Date();
const date = new Date(Date.UTC(currentdate.getFullYear(), (currentdate.getMonth()),currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), currentdate.getSeconds()));
//you can pass YY, MM, DD //op: 2018-03-01
//i have passed YY, MM, DD, HH, Min, Sec // op : 2021-06-09T12:14:27.000Z
console.log(date.toISOString());
output will be similar to this : 2021-06-09T12:14:27.000Z
const month = date.toLocaleDateString('en-US', { month: '2-digit' });
const day = date.toLocaleDateString('en-US', { day: '2-digit' });
const year = date.getFullYear();
const dateString = `${month}-${day}-${year}`;
The following aims to extract configuration, hook into Date.protoype and apply configuration.
I've used an Array to store time chunks and when I push() this as a Date object, it returns me the length to iterate. When I'm done, I can use join on the return value.
This seems to work pretty fast: 0.016ms
// Date protoype
Date.prototype.formatTime = function (options) {
var i = 0,
time = [],
len = time.push(this.getHours(), this.getMinutes(), this.getSeconds());
for (; i < len; i += 1) {
var tick = time[i];
time[i] = tick < 10 ? options.pad + tick : tick;
}
return time.join(options.separator);
};
// Setup output
var cfg = {
fieldClock: "#fieldClock",
options: {
pad: "0",
separator: ":",
tick: 1000
}
};
// Define functionality
function startTime() {
var clock = $(cfg.fieldClock),
now = new Date().formatTime(cfg.options);
clock.val(now);
setTimeout(startTime, cfg.options.tick);
}
// Run once
startTime();
demo: http://jsfiddle.net/tive/U4MZ3/
Add some padding to allow a leading zero - where needed - and concatenate using your delimiter of choice as string.
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
var d = new Date(my_date);
var dformatted = [(d.getMonth()+1).padLeft(), d.getDate().padLeft(), d.getFullYear()].join('/');
let date = new Date();
let dd = date.getDate();//day of month
let mm = date.getMonth();// month
let yyyy = date.getFullYear();//day of week
if (dd < 10) {//if less then 10 add a leading zero
dd = "0" + dd;
}
if (mm < 10) {
mm = "0" + mm;//if less then 10 add a leading zero
}
function pad(value) {
return value.tostring().padstart(2, 0);
}
let d = new date();
console.log(d);
console.log(`${d.getfullyear()}-${pad(d.getmonth() + 1)}-${pad(d.getdate())}t${pad(d.gethours())}:${pad(d.getminutes())}:${pad(d.getseconds())}`);
You can use String.slice() which extracts a section of a string and returns it as a new string, without modifying the original string:
const currentDate = new Date().toISOString().slice(0, 10) // 2020-04-16
Or you can also use a lib such as Moment.js to format the date:
const moment = require("moment")
const currentDate = moment().format("YYYY-MM-DD") // 2020-04-16
A simple dateformat library saved my life (GitHub):
Node.js: var dateFormat = require("dateformat");
ES6: import dateFormat from "dateformat";
const now = new Date(); // consider 3rd of December 1993
const full = dateFormat(today, "yyyy-mm-dd"); // 1993-12-03
const day = dateFormat(today, "dd"); // 03
const month = dateFormat(today, "mm"); // 12
const year = dateFormat(today, "yyyy"); // 1993
It's worth to mention it supports a wide range of mask options.
Here's the code I'm working on:
function populateDates() {
var start = new Date(2017, 7, 13);
var end = new Date(2017, 8, 3);
var tempDate = start;
var endPlus90 = end.setDate(end.getDate() + 90);
var today = new Date();
var array = [];
for(var d = start; d < today || d < endPlus90; d.setDate(d.getDate() + 1)){
if (d.getDay() !== 0 && d.getDay() !== 6){
array.push([d]);
}
}
return array;
}
var future = new Date();
future.setDate(future.getDate() + 90);
console.log(populateDates(new Date(), future));
Basically, what I'm trying to do is, given an arbitrary start and end date, generate a list of dates, excluding weekends, from the start date to either 90 days after the end date, or the current date, whichever is earlier. The current function generates an array that is all identical dates which are 90 days after the end date. I'm not very familiar with Javascript, so I'm not sure what's going wrong here. I suspect that the way I'm pushing the variable to the array is incorrect.
The problem comes with your usage of setDate which returns
The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the Date object is also changed in place).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate
Wrap that setDate line in a new Date() and your code should run just fine.
As others pointed out the reason the array had multiples of the same date is because you were pushing references to the same single date object, and reassigning that object's date, which was updating it each of these references. By creating a new Date with new Date() you are creating a new object with its own reference.
Try this out. You need to initialize the d to a new Date every time. You can't just change the day. You also need to put new Date() around end.setDate(). setDate() returns milliseconds.
function populateDates(start, end) {
var tempDate = start;
var endPlus90 = new Date(end.setDate(end.getDate() + 90));
var today = new Date();
var array = [];
for(var d = tempDate; d < endPlus90; d = new Date(d.setDate(d.getDate() + 1))){
if(d >= today) { // Stop counting dates if we reach the current date
break;
}
if (d.getDay() !== 0 && d.getDay() !== 6){
array.push([d]);
}
}
return array;
}
var future = new Date(); // As of 10/18/2017
future.setDate(future.getDate() + 90);
console.log(populateDates(new Date(2017, 9, 1), future)); // Prints 13 days as of 10/18/2017
console.log(populateDates(new Date(2016, 9, 1), future)); // Prints 273 days
Before I am using angularjs-DatePicker from this npm.
Here,I am able to select the date from the date picker.But now I have to fields as FromDate and ToDate which means the week StartDate and EndDate should show when any date pick in that week.
Ex: Like in Calender 01-08-2017 Start on Tue, So whenever Selects Any date from 01 to 05 then the two fields should show as FromDate as 01 and TODate as 06 and in the same whenever the user selects the 31-07-2017 the the Two fields should show as 30 and 31 of july.
I have an idea to achieve the ToDate from FromDate Calender control onchange event in DotNet as like below mentioned code
Convert.ToDouble(objstart.DayOfWeek)).ToString("dd-MM-yyyy")
But how to achieve this usecase in the angularjs.
Thanks
Ok, so what I'd do is to calculate different dates, and take the min/max depending on the start or end of the week.
Here:
//Use the date received, UTC to prevent timezone making dates shift
var pickedDate = new Date("08-03-2017UTC");
var startSunday = new Date(pickedDate);
startSunday.setDate(pickedDate.getDate() - pickedDate.getDay());
var startMonth = new Date(pickedDate);
startMonth.setDate(1);
var startDate = Math.max(startMonth,startSunday);
console.log("Start:" , new Date(startDate));
var endSaturday = new Date(pickedDate);
endSaturday.setDate(pickedDate.getDate() + (7-pickedDate.getDay()));
var endMonth = new Date(pickedDate);
endMonth.setMonth(pickedDate.getMonth()+1);//Add a month
endMonth.setDate(0);// to select last day of previous month.
var endDate = Math.min(endMonth,endSaturday);
console.log("End" , new Date(endDate));
The trick was to play with the dates, find all the possible start and end dates, then choose the right one with Math.min and Math.max which will compare the dates using their timestamp.
There is very good Library available in JavaScript to handle Date Manipulations.
https://github.com/datejs/Datejs
There is a method
Date.parse('next friday') // Returns the date of the next Friday.
Date.parse('last monday')
Using these method you can get the start and ending date of the week based on the current week.
I hope that it will help.
You can simply achieve this using the library moment. There are a lot of useful functions in this library.
var selectedDate = moment('Mon Aug 10 2017');
//If you want to get the ISO week format(Monday to Sunday)
var weekStart = selectedDate.clone().startOf('isoweek').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('isoweek').format('MMM Do');
//If you want to get the Sunday to Saturday week format
var weekStart = selectedDate.clone().startOf('week').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('week').format('MMM Do');
No need angular directive here, you could use the JavaScript extension which is below.
//get week from date
Date.prototype.getWeekNumber = function (weekstart) {
var target = new Date(this.valueOf());
// Set default for weekstart and clamp to useful range
if (weekstart === undefined) weekstart = 1;
weekstart %= 7;
// Replaced offset of (6) with (7 - weekstart)
var dayNr = (this.getDay() + 7 - weekstart) % 7;
target.setDate(target.getDate() - dayNr + 0);//0 means friday
var firstDay = target.valueOf();
target.setMonth(0, 1);
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstDay - target) / 604800000);;
};
//get date rance of week
Date.prototype.getDateRangeOfWeek = function (weekNo, weekstart) {
var d1 = this;
var firstDayOfWeek = eval(d1.getDay() - weekstart);
d1.setDate(d1.getDate() - firstDayOfWeek);
var weekNoToday = d1.getWeekNumber(weekstart);
var weeksInTheFuture = eval(weekNo - weekNoToday);
var date1 = angular.copy(d1);
date1.setDate(date1.getDate() + eval(7 * weeksInTheFuture));
if (d1.getFullYear() === date1.getFullYear()) {
d1.setDate(d1.getDate() + eval(7 * weeksInTheFuture));
}
var rangeIsFrom = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
d1.setDate(d1.getDate() + 6);
var rangeIsTo = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
return { startDate: rangeIsFrom, endDate: rangeIsTo }
};
Your code can be look like this
var startdate = '01-08-2017'
var weekList = [];
var year = startdate.getFullYear();
var onejan = new Date(year, 0, 1);//first january is the first week of the year
var weekstart = onejan.getDay();
weekNumber = startdate.getWeekNumber(weekstart);
//generate week number
var wkNumber = weekNumber;
var weekDateRange = onejan.getDateRangeOfWeek(wkNumber, weekstart);
var wk = {
value: wkNumber
, text: 'Week' + wkNumber.toString()
, weekStartDate: new Date(weekDateRange.startDate)
, weekEndDate: new Date(weekDateRange.endDate)
};
weekList.push(wk);
I guess there is no directive or filter for this, you need to create one for yourself. you can refer date object from date-time-object
In Javascript, how do I get the number of weeks in a month? I can't seem to find code for this anywhere.
I need this to be able to know how many rows I need for a given month.
To be more specific, I would like the number of weeks that have at least one day in the week (a week being defined as starting on Sunday and ending on Saturday).
So, for something like this, I would want to know it has 5 weeks:
S M T W R F S
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Thanks for all the help.
Weeks start on Sunday
This ought to work even when February doesn't start on Sunday.
function weekCount(year, month_number) {
// month_number is in the range 1..12
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var used = firstOfMonth.getDay() + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
Weeks start on Monday
function weekCount(year, month_number) {
// month_number is in the range 1..12
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var used = firstOfMonth.getDay() + 6 + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
Weeks start another day
function weekCount(year, month_number, startDayOfWeek) {
// month_number is in the range 1..12
// Get the first day of week week day (0: Sunday, 1: Monday, ...)
var firstDayOfWeek = startDayOfWeek || 0;
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var numberOfDaysInMonth = lastOfMonth.getDate();
var firstWeekDay = (firstOfMonth.getDay() - firstDayOfWeek + 7) % 7;
var used = firstWeekDay + numberOfDaysInMonth;
return Math.ceil( used / 7);
}
None of the solutions proposed here don't works correctly, so I wrote my own variant and it works for any cases.
Simple and working solution:
/**
* Returns count of weeks for year and month
*
* #param {Number} year - full year (2016)
* #param {Number} month_number - month_number is in the range 1..12
* #returns {number}
*/
var weeksCount = function(year, month_number) {
var firstOfMonth = new Date(year, month_number - 1, 1);
var day = firstOfMonth.getDay() || 6;
day = day === 1 ? 0 : day;
if (day) { day-- }
var diff = 7 - day;
var lastOfMonth = new Date(year, month_number, 0);
var lastDate = lastOfMonth.getDate();
if (lastOfMonth.getDay() === 1) {
diff--;
}
var result = Math.ceil((lastDate - diff) / 7);
return result + 1;
};
you can try it here
This is very simple two line code. and i have tested 100%.
Date.prototype.getWeekOfMonth = function () {
var firstDay = new Date(this.setDate(1)).getDay();
var totalDays = new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
return Math.ceil((firstDay + totalDays) / 7);
}
How to use
var totalWeeks = new Date().getWeekOfMonth();
console.log('Total Weeks in the Month are : + totalWeeks );
You'll have to calculate it.
You can do something like
var firstDay = new Date(2010, 0, 1).getDay(); // get the weekday january starts on
var numWeeks = 5 + (firstDay >= 5 ? 1 : 0); // if the months starts on friday, then it will end on sunday
Now we just need to genericize it.
var dayThreshold = [ 5, 1, 5, 6, 5, 6, 5, 5, 6, 5, 6, 5 ];
function GetNumWeeks(month, year)
{
var firstDay = new Date(year, month, 1).getDay();
var baseWeeks = (month == 1 ? 4 : 5); // only February can fit in 4 weeks
// TODO: account for leap years
return baseWeeks + (firstDay >= dayThreshold[month] ? 1 : 0); // add an extra week if the month starts beyond the threshold day.
}
Note: When calling, remember that months are zero indexed in javascript (i.e. January == 0).
function weeksinMonth(m, y){
y= y || new Date().getFullYear();
var d= new Date(y, m, 0);
return Math.floor((d.getDate()- 1)/7)+ 1;
}
alert(weeksinMonth(3))
// the month range for this method is 1 (january)-12(december)
The most easy to understand way is
<div id="demo"></div>
<script type="text/javascript">
function numberOfDays(year, month)
{
var d = new Date(year, month, 0);
return d.getDate();
}
function getMonthWeeks(year, month_number)
{
var $num_of_days = numberOfDays(year, month_number)
, $num_of_weeks = 0
, $start_day_of_week = 0;
for(i=1; i<=$num_of_days; i++)
{
var $day_of_week = new Date(year, month_number, i).getDay();
if($day_of_week==$start_day_of_week)
{
$num_of_weeks++;
}
}
return $num_of_weeks;
}
var d = new Date()
, m = d.getMonth()
, y = d.getFullYear();
document.getElementById('demo').innerHTML = getMonthWeeks(y, m);
</script>
using moment js
function getWeeksInMonth(year, month){
var monthStart = moment().year(year).month(month).date(1);
var monthEnd = moment().year(year).month(month).endOf('month');
var numDaysInMonth = moment().year(year).month(month).endOf('month').date();
//calculate weeks in given month
var weeks = Math.ceil((numDaysInMonth + monthStart.day()) / 7);
var weekRange = [];
var weekStart = moment().year(year).month(month).date(1);
var i=0;
while(i<weeks){
var weekEnd = moment(weekStart);
if(weekEnd.endOf('week').date() <= numDaysInMonth && weekEnd.month() == month) {
weekEnd = weekEnd.endOf('week').format('LL');
}else{
weekEnd = moment(monthEnd);
weekEnd = weekEnd.format('LL')
}
weekRange.push({
'weekStart': weekStart.format('LL'),
'weekEnd': weekEnd
});
weekStart = weekStart.weekday(7);
i++;
}
return weekRange;
} console.log(getWeeksInMonth(2016, 7))
ES6 variant, using consistent zero-based months index. Tested for years from 2015 to 2025.
/**
* Returns number of weeks
*
* #param {Number} year - full year (2018)
* #param {Number} month - zero-based month index (0-11)
* #param {Boolean} fromMonday - false if weeks start from Sunday, true - from Monday.
* #returns {number}
*/
const weeksInMonth = (year, month, fromMonday = false) => {
const first = new Date(year, month, 1);
const last = new Date(year, month + 1, 0);
let dayOfWeek = first.getDay();
if (fromMonday && dayOfWeek === 0) dayOfWeek = 7;
let days = dayOfWeek + last.getDate();
if (fromMonday) days -= 1;
return Math.ceil(days / 7);
}
You could use my time.js library. Here's the weeksInMonth function:
// http://github.com/augustl/time.js/blob/623e44e7a64fdaa3c908debdefaac1618a1ccde4/time.js#L67
weeksInMonth: function(){
var millisecondsInThisMonth = this.clone().endOfMonth().epoch() - this.clone().firstDayInCalendarMonth().epoch();
return Math.ceil(millisecondsInThisMonth / MILLISECONDS_IN_WEEK);
},
It might be a bit obscure since the meat of the functionality is in endOfMonth and firstDayInCalendarMonth, but you should at least be able to get some idea of how it works.
This works for me,
function(d){
var firstDay = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
return Math.ceil((d.getDate() + (firstDay - 1))/7);
}
"d" should be the date.
A little rudimentary, yet should cater for original post :
/**
* #param {date} 2020-01-30
* #return {int} count
*/
this.numberOfCalendarWeekLines = date => {
// get total
let lastDayOfMonth = new Date( new Date( date ).getFullYear(), new Date( date ).getMonth() + 1, 0 );
let manyDaysInMonth = lastDayOfMonth.getDate();
// itterate through month - from 1st
// count calender week lines by occurance
// of a Saturday ( s m t w t f s )
let countCalendarWeekLines = 0;
for ( let i = 1; i <= manyDaysInMonth; i++ ) {
if ( new Date( new Date( date ).setDate( i ) ).getDay() === 6 ) countCalendarWeekLines++;
}
// days after last occurance of Saturday
// leaked onto new line?
if ( lastDayOfMonth.getDay() < 6 ) countCalendarWeekLines++;
return countCalendarWeekLines;
};
Thanks to Ed Poor for his solution, this is the same as Date prototype.
Date.prototype.countWeeksOfMonth = function() {
var year = this.getFullYear();
var month_number = this.getMonth();
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var used = firstOfMonth.getDay() + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
So you can use it like
var weeksInCurrentMonth = new Date().countWeeksOfMonth();
var weeksInDecember2012 = new Date(2012,12,1).countWeeksOfMonth(); // 6
function getWeeksInMonth(month_number, year) {
console.log("year - "+year+" month - "+month_number+1);
var day = 0;
var firstOfMonth = new Date(year, month_number, 1);
var lastOfMonth = new Date(year, parseInt(month_number)+1, 0);
if (firstOfMonth.getDay() == 0) {
day = 2;
firstOfMonth = firstOfMonth.setDate(day);
firstOfMonth = new Date(firstOfMonth);
} else if (firstOfMonth.getDay() != 1) {
day = 9-(firstOfMonth.getDay());
firstOfMonth = firstOfMonth.setDate(day);
firstOfMonth = new Date(firstOfMonth);
}
var days = (lastOfMonth.getDate() - firstOfMonth.getDate())+1
return Math.ceil( days / 7);
}
It worked for me. Please try
Thanks all
This piece of code give you the exact number of weeks in a given month:
Date.prototype.getMonthWeek = function(monthAdjustement)
{
var firstDay = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
var returnMessage = (Math.ceil(this.getDate()/7) + Math.floor(((7-firstDay)/7)));
return returnMessage;
}
The monthAdjustement variable adds or substract the month that you are currently in
I use it in a calendar project in JS and the equivalent in Objective-C and it works well
function weekCount(year, month_number, day_start) {
// month_number is in the range 1..12
// day_start is in the range 0..6 (where Sun=0, Mon=1, ... Sat=6)
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var dayOffset = (firstOfMonth.getDay() - day_start + 7) % 7;
var used = dayOffset + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
I know this is coming late, I have seen codes upon codes trying to get the number of weeks a particular month falls on, but many have not been really precise but most have been really informative and reusable, I'm not an expert programmer but I can really think and thanks to some codes by some people I was able to arrive at a conclusion.
function convertDate(date) {//i lost the guy who owns this code lol
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth()+1).toString();
var dd = date.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}
//this line of code from https://stackoverflow.com/a/4028614/2540911
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var myDate = new Date('2019-03-2');
//var myDate = new Date(); //or todays date
var c = convertDate(myDate).split("-");
let yr = c[0], mth = c[1], dy = c[2];
weekCount(yr, mth, dy)
//Ahh yes, this line of code is from Natim Up there, incredible work, https://stackoverflow.com/a/2485172/2540911
function weekCount(year, month_number, startDayOfWeek) {
// month_number is in the range 1..12
console.log(weekNumber);
// Get the first day of week week day (0: Sunday, 1: Monday, ...)
var firstDayOfWeek = startDayOfWeek || 0;
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var numberOfDaysInMonth = lastOfMonth.getDate();
var first = firstOfMonth.getDate();
//initialize first week
let weekNumber = 1;
while(first-1 < numberOfDaysInMonth){
// add a day
firstOfMonth = firstOfMonth.setDate(firstOfMonth.getDate() + 1);//this line of code from https://stackoverflow.com/a/9989458/2540911
if(days[firstOfMonth.getDay()] === "Sunday"){//get new week every new sunday according the local date format
//get newWeek
weekNumber++;
}
if(weekNumber === 3 && days[firstOfMonth.getDay()] === "Friday")
alert(firstOfMonth);
first++
}
}
I needed this code to generate a schedule or event scheduler for a church on every 3rd friday of a new month, so you can modify this to suit your or just pick your specific date, not "friday and specify the week of the month and Voila!! here you go
None of the solutions here really worked for me. Here is my crack at it.
// Example
// weeksOfMonth(2019, 9) // October
// Result: 5
weeksOfMonth (year, monthIndex) {
const d = new Date(year, monthIndex+ 1, 0)
const adjustedDate = d.getDate() + d.getDay()
return Math.ceil(adjustedDate / 7)
}
Every solutions helped but nothing was working for me so I did my own with moment library :
const getWeeksInAMonth = (currentDate: string) => {
const startOfMonth = moment(currentDate).startOf("month")
const endOfMonth = moment(currentDate).endOf("month")
return moment(endOfMonth).week() - moment(startOfMonth).week() + 1
}
Please anyone share the code to find the previous month's first date from current date in JavaScript. For example, if the current date is 25th Jan 2009, I should get 1st Dec 2008 as result.
Straightforward enough, with the date methods:
var x = new Date();
x.setDate(1);
x.setMonth(x.getMonth()-1);
Simplest way would be:
var x = new Date();
x.setDate(0); // 0 will result in the last day of the previous month
x.setDate(1); // 1 will result in the first day of the month
Deals with updating year when moving from January to December
var prevMonth = function(dateObj) {
var tempDateObj = new Date(dateObj);
if(tempDateObj.getMonth) {
tempDateObj.setMonth(tempDateObj.getMonth() - 1);
} else {
tempDateObj.setYear(tempDateObj.getYear() - 1);
tempDateObj.setMonth(12);
}
return tempDateObj
};
var wrapper = document.getElementById('wrapper');
for(var i = 0; i < 12; i++) {
var x = new Date();
var prevDate = prevMonth(x.setMonth(i));
var div = document.createElement('div');
div.textContent =
"start month/year: " + i + "/" + x.getFullYear() +
" --- prev month/year: " + prevDate.getMonth() +
"/" + prevDate.getFullYear() +
" --- locale prev date: " + prevDate.toLocaleDateString();
wrapper.appendChild(div);
}
<div id='wrapper'>
</div>
Important Note: Some of the answers using setMonth() here are wrong:
One liners for use in 2019 (using ES6 syntax; supported by all major browsers and Node):
const date = new Date().toISOString(); // "2019-09-18T13:49:12.775Z"
const [yyyy, mm, dd, h, i, s] = date.split(/T|:|-/);
// previous month's last day
const prev = new Date(new Date().setDate(0)).toISOString();
const [pyyyy, pmm] = prev.split(/T|:|-/);
Note that Array destructuring allows you to skip parts:
const date = new Date().toISOString();
const [, , dd, , i] = date.split(/T|:|-/);
Explanation: The code above gets the ISO date 2019-09-18T13:49:12.775Z and splits it on : or - or T which returns an array [2019, 09, 18, 13, 49, 12] which then gets destructured.
Using setMonth() is wrong:
date = new Date("Dec 31, 2019")
date.setMonth(date.getMonth() - 1);
date; // Dec 1, 2019!
This worked for me
var curDateMonth = new Date();
var prvDateMonth = new Date(curDateMonth.getFullYear(),curDateMonth.getMonth()-1,curDateMonth.getMonth());
console.log(curDateMonth.toLocaleString('en-US', { month: 'long' }) +' vs '+ prvDateMonth.toLocaleString('en-US', { month: 'long' }));
Check this link:
http://blog.dansnetwork.com/2008/09/18/javascript-date-object-adding-and-subtracting-months/
EDIT: I have drummed up an example:
Date.prototype.SubtractMonth = function(numberOfMonths) {
var d = this;
d.setMonth(d.getMonth() - numberOfMonths);
d.setDate(1);
return d;
}
$(document).ready(function() {
var d = new Date();
alert(d.SubtractMonth(1));
});
To get 00:00:00 am of previous month use this:
let d = new Date();
d.setDate(1);
d.setMonth(d.getMonth() - 1);
d.setHours(0,0,0,0);
const lastMonthStart = new Date(d);
Hope this helps!!
// Previous Month Detail
let prevStartDate = new Date(this.date.getFullYear(), this.date.getMonth() - 1, 1);
console.log(prevStartDate);
let preEndDate = new Date(this.date.getFullYear(), this.date.getMonth() - 1 + 1, 0);
console.log(preEndDate);
//Current Month Detail
let cStartDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1);
console.log(cStartDate);
let cEndDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0);
console.log(cEndDate);
//Next Month Detail
let nStartDate = new Date(this.date.getFullYear(), this.date.getMonth() + 1, 1);
console.log(nStartDate);
let nendDate = new Date(this.date.getFullYear(), this.date.getMonth() + 1 + 1, 0);
console.log(nendDate);
//just try this will work fine
let date = new Date();
let month = new Date().getMonth();
let prevMonth = date.setMonth(month - 1)
let formatPrevMonth = new Date(date.setMonth(month - 1));
console.log(formatPrevMonth)
Here, first we assign getMonth() to a variable and incremented it by 1:
var currentMonth = date.getMonth()+1;
var current_date = date.getFullYear()+"/"+currentMonth+"/"+date.getDate();
document.getElementById("p3").innerHTML = "Today,s date:"+current_date;
This can easily be achieved by creating a Date object based on the input date object and changing the date to 1, decrementing the year if it was January and decrementing the month (modulo 12). An important addition to it is to subtract the offset as well.
function getFirstOfPreviousMonth(date) {
let result = new Date(date.getFullYear() - (date.getMonth() ? 0 : 1), (date.getMonth() + 11) % 12, 1);
return new Date(result.getTime() - result.getTimezoneOffset() * 60000);
}
console.log(getFirstOfPreviousMonth(new Date()));
console.log(getFirstOfPreviousMonth(new Date(2009, 0, 25)));