momentjs getting the week days of a target date - javascript

I'm using momentjs to work with dates, I get the current week using:
var startDate = moment().startOf('isoweek');
var endDate = moment().endOf('isoweek');
var weekDays = getWeekDays(startDate, endDate);
where the function getWeekDays is implemented as the follow:
function getWeeDays(startDate, endDate) {
"use strict";
var days = [];
var day = startDate;
while (day <= endDate) {
days.push(day);
day = day.clone().add(1, 'd');
}
return days;
}
This works pretty well, but now i need to get the days not of the current week but of the week of a target date.
For example the user input me the date 24/05/2016 and i need to get te days starting from Monday 23 May 2016 to Sunday 29 May 2016.
I have tried:
var startDate = moment().startOf('isoweek').year(year).month(month).day(day);
var endDate = moment().endOf('isoweek').year(year).month(month).day(day);
var weekDays = getWeekDays(startDate, endDate);
where the variable year, month and day are equals in this example to: 2016, 05, 24. This doesn't work. Do you have any suggestions using momentjs Or how to do it without using momentjs?
UPDATE
Ok I solved it myself! Sorry for the posted question, i put the solution here ( First check is the date is valid!):
if(moment(year + "/" + month + "/" + day, "YYYY/MM/DD", true).isValid()){
var startDate = moment(year + "/" + month + "/" + day, "YYYY/MM/DD").startOf('isoweek');
var endDate = moment(year + "/" + month + "/" + day, "YYYY/MM/DD").endOf('isoweek');
var weekDays = getWeekDays(startDate, endDate);
}

This is what i did to solve the problem:
if(moment(year + "/" + month + "/" + day, "YYYY/MM/DD", true).isValid()){
var startDate = moment(year + "/" + month + "/" + day, "YYYY/MM/DD").startOf('isoweek');
var endDate = moment(year + "/" + month + "/" + day, "YYYY/MM/DD").endOf('isoweek');
var weekDays = getWeekDays(startDate, endDate);
}
function getWeeDays(startDate, endDate) {
"use strict";
var days = [];
var day = startDate;
while (day <= endDate) {
days.push(day);
day = day.clone().add(1, 'd');
}
return days;
}

`moment(anyValidDate).day()`
// will return you the index of the day of given date.
//i.e. 0 for Sunday, 1 for Monday and so on till 6 for Saturday. list of week days.
new Date().getDay() // will give same result as above.
next you know what to do.

Related

Javascript n months after today

I am trying to get the day 90 days after today. This is my code:
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
When I print threeMonthsFromToday, I get the correct date: 2017-04-24T15:17:42.641Z. However, when I try to reformat the date to be in the form dd/mm/yyyy using this code:
var day = ('0' + threeMonthsFromToday.getDate()).slice(-2);
var month = ('0' + threeMonthsFromToday.getMonth() + 1).slice(-2);
var year = threeMonthsFromToday.getFullYear();
var date = day + '/' + month + '/' + year;
I get a completely different and invalid date: 24/31/2017.
I have been debugging this for hours and still can't seem to figure what I am doing wrong.
Well, '0' + threeMonthsFromToday.getMonth() give you a string : "03" then you add 1 converted to string giving you "031" for month before slice.
Use this :
var month = ('0' + (threeMonthsFromToday.getMonth() + 1)).slice(-2);
You are missing the basic BODMAS rule here please modify your code as follows
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
var day = ('0' + threeMonthsFromToday.getDate()).slice(-2);
var month = ('0' + (threeMonthsFromToday.getMonth() + 1)).slice(-2);
var year = threeMonthsFromToday.getFullYear();
var date = day + '/' + month + '/' + year;
the operations are performed from left to right, so month is getting converted to string before being added to a number. Including a bracket will first perform operation inside bracket and then make it a string
Can you use toLocaleString?
threeMonthsFromToday.toLocaleDateString('en-GB')
Below does the trick for you ...
getMonth() +1 before adding the "0" to it so that you get an arithematic +1
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
var day = ('0' + threeMonthsFromToday.getDate()).slice(-2);
var month = ('0' + (threeMonthsFromToday.getMonth()+1)).slice(-2);
var year = threeMonthsFromToday.getFullYear();
var date = day + '/' + month + '/' + year;
console.log(date);
This should work.
var day = threeMonthsFromToday.getDate()
if(day < 10){
day = '0' + day
}
var month = threeMonthsFromToday.getMonth()+1
if(month<10){
month = '0' + month
}
var year = threeMonthsFromToday.getFullYear()
var date = day + '/' + month + '/' + year
Use Simple toLocaleDateString method
The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date.
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
var date = threeMonthsFromToday.toLocaleDateString();
console.log(date);
//result in console : "24/04/2017"
Try it out on your console.

Any built-in method to get boundary dates for a date in day, week and month view in a calendar?

I need to send boundary dates of a selected date(from a date picker) to the server based on present view is Day or Week or Month. Example as shown given below
Ex:
If the day is 25-01-2016 and
1. In "Day" View I need to send :
fromDate: "25012016",
toDate:"25012016"
2. "Week" view(consider Monday as first day of the week as the calendar view in my screen showing the same) :
fromDate: "25012016",
toDate:"31012016"
3."Month" view:
fromDate: "01012016",
toDate:"31012016"
Not aware of any built in function but you can easily get
var currentDate = new Date();
var dayOfWeek = currentDate.getDay();
Week
//var currentDate = new Date();
var currentDate = new Date(2016,0,19);
var dayOfWeek = currentDate.getDay();
console.log( dayOfWeek );
dayOfWeek = (dayOfWeek + 6 )%7; //calibrate it for Monday to Sunday
currentDate.setDate( currentDate.getDate() + (-dayOfWeek ) ); //first day of week accomodating +1 for making Monday as first day
document.body.innerHTML += "<br>" + currentDate.toString();
currentDate.setDate( currentDate.getDate() + 7 ); //last day of week
document.body.innerHTML += "<br>" + currentDate.toString();
Month
currentDate = new Date();
currentDate.setDate( 1 ); //first day of current month
document.body.innerHTML += "<br>" + currentDate.toString();
currentDate.setMonth( currentDate.getMonth() + 1 ); //first day of next month
currentDate.setDate( currentDate.getDate() + (-1) ); //last day of current month
document.body.innerHTML += "<br>" + currentDate.toString();
Thanks all for the help!
With Momentjs, I did my job.
// type can be "Day" or "Week" or "Month"
var getBoundaryDates = function(selecteddate, type){
var fromd = moment(selecteddate).startOf(type).format('YYYY-MM-DD');
var tod = moment(selectddate).endOf(type).format('YYYY-MM-DD');
if(type == 'Week') {
var dayToSubtract = selecteddate.getDay() == 0 ? 7 : selecteddate.getDay();
fromd = moment(new Date(selecteddate).setDate((selecteddate.getDate() - dayToSubtract) +1)).format('YYYY-MM-DD');
tod = moment(new Date(selecteddate).setDate((selecteddate.getDate() - dayToSubtract) +7)).format('YYYY-MM-DD');
}
return {
fromd : fromd,
tod : tod
}
}

A twofold javascript function to convert a long date and return today's date in mm-dd-yyyy format

I need your help,
I can't seem to find any other help on this on the internet, because it seems its either one way ot the other. What I would like to be able to do is to create a combined, two-fold javascript function that would convert a long date string into the mm-dd-yyyy format, and when the same function is called again with no string specified to convert, to just return todays date in mm-dd-yyyy format.
Example:
getDate(Fri May 22 2015 13:32:25 GMT-0400)
would return: 05-22-2015
getDate()
would return today's date of 05-23-2015
Hi this should do the trick
FORMAT: mm-dd-yyyy
function addZeroIfRequired(dayOrMonth) {
return dayOrMonth > 9 ? dayOrMonth : "0"+dayOrMonth;
}
function getDate(dateString) {
var date = dateString ? new Date(dateString) : new Date();
return addZeroIfRequired((date.getUTCMonth()+1)) + "-" +
addZeroIfRequired(date.getDate())+ "-" +
date.getUTCFullYear();
}
console.log(getDate()); // 05-23-2015
console.log(getDate("Fri May 22 2015 13:32:25 GMT-0400")); 05-22-2015
NOTE: the +1 after the getUTCMonth().
JSFiddle. Open the console to see the result. https://jsfiddle.net/wt79yLo0/2/
ISO FORMAT: yyyy-mm-dd
Just in case someone is interested in the opposite format, the code would be much nicer and neater:
function getDate(dateString) {
var date = dateString ? new Date(dateString) : new Date();
return date.toISOString().substring(0, 10);
}
console.log(getDate());
console.log(getDate("Fri May 22 2015 13:32:25 GMT-0400"));
https://jsfiddle.net/wt79yLo0/
First I would recommend a very powerful library for JS called Moment.js which solves all this kind of problems.
But if you only want a snippet, here is my proposal:
function twoDigits(num) {
return ("0" + num).substr(-2);
}
function getFormattedDateDMY(date, separator) {
var day = twoDigits(date.getDate());
var month = twoDigits(date.getMonth());
var year = date.getFullYear();
return [day,month,year].join(separator);
}
function getFormattedDateMDY(date, separator) {
var day = twoDigits(date.getDate());
var month = twoDigits(date.getMonth());
var year = date.getFullYear();
return [month,day,year].join(separator);
}
console.log(getFormattedDateDMY(new Date(), "-")); //23-04-2015
console.log(getFormattedDateMDY(new Date(), "-")); //04-23-2015
With getDate(), getMonth() and getFullYear(). You have to set a "0" before the months and days which are < 10. GetMonth() starts with 0, therefore (getMonth() + 1).
function getFormattedDate() {
var date = new Date();
var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
var year = date.getFullYear();
var formattedDate = day + "-" + month + "-" + year;
return formattedDate;
}
console.log(getFormattedDate());
Demo

Change date range in javascript

I am trying to set start and end date in date picker where start date is week before current date and end date is week after start date. In certain condition it gives me 0 for start date. Can anyone look into code below and help me to get proper date range when current date is first day of the month or last date of the month. Thanks for your help.
var date = new Date();
//When current date was less then 7 in some situation it giving me error. So, I am checking current date and randomly subtract 3.
//if current date is less then 7 then get the last day of the previous month
if (date.getDate() <= 7) {
day = new Date(date.getFullYear(), date.getMonth(), 0);
startdate = day.getDate() - 3;
month = day.getMonth() + 1;
year = day.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = day;
console.log("App Config: lasy day: " + startdate + "\nmonth: " + month + "\nyear:" + year);
}
else {
startdate = date.getDate() - 7;
month = date.getMonth() + 1;
year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = day;
console.log("App Config: day: " + startdate + "\nmonth: " + month + "\nyear:" + year);
}
return month + "/" + startdate + "/" + year;
Have you tried this:
var dt = new Date();
var weekBefore = dt.setDate(dt.getDate() - 7);
var weekAfter = dt.setDate(dt.getDate() + 7);
JavaScript will figure it out automatically the date 7 days before and after!
If you are ok with plugins I would suggest Moment.js which is great for date handling. Adding a week would be as easy as
var inOneWeek = moment().add(1, 'weeks');//.format('DD/MM/YYYY'); if u want it in DD/MM/YYYY format
var oneWeekAgo = moment().add(-1, 'weeks');//.format('DD/MM/YYYY');
otherwise #sabotero's answer would do as well.

How can I format a json date in dd/mm/yy format in javascript?

I have a json date like \/Date(1334514600000)\/ in my response and when I convert it in javascript then I got this date Tue Apr 17 2012 11:37:10 GMT+0530 (India Standard Time),
but I need the date format like 17/04/2012 and I fail every time. Can anyone tell me how can I resolve it?
I don't think that the other posted answers are quite right, you have already accepted one as working for you so I won't edit it.
Here is an updated version of your accepted answer.
var dateString = "\/Date(1334514600000)\/".substr(6);
var currentTime = new Date(parseInt(dateString ));
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
alert(date);
It uses a technique from this answer to extract the epoch from the JSON date.
I found very helpful the row1 answer, however i got stuck on the format for input type="date" as only returns one string for decimals under 10, I was able to modify to work on input type="date", I basically adapted the code from row1 to the code from the link http://venkatbaggu.com/convert-json-date-to-date-format-in-jquery/
I was able through jquery .val add the date to the input
var dateString = "\/Date(1334514600000)\/".substr(6);
var currentTime = new Date(parseInt(dateString));
var month = ("0" + (currentTime.getMonth() + 1)).slice(-2);
var day = ("0" + currentTime.getDate()).slice(-2);
var year = currentTime.getFullYear();
var date = year + '-' + month + '-' + day;
alert(date);
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var date = day + "/" + month + "/" + year
alert(date);
It's answer to your question...
Build the date object with your timestamp
var currentTime = new Date(1334514600000)
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var date = day + "/" + month + "/" + year
alert(date);​
it works
http://jsfiddle.net/ChgUa/
//parse JSON formatted date to javascript date object
var bdate = new Date(parseInt(emp.Birthdate.substr(6)));
//format display date (e.g. 04/10/2012)
var displayDate = $.datepicker.formatDate("mm/dd/yy", bdate);
Easiest way of formatting date is by using pipes if you are using Angular.
Click here
//in .ts file
ngOnInit() {
this.currentDate = new Date()
}
//in html file
<p>Current date is:</p>{{currentDate | date: 'dd/MM/yyyy'}}
//Output: 22/04/2020
Here is an updated version of your accepted answer. DD/MM/YYYY Format Get Try This..
var dateString = "/Date(1623781800000+0530)/"+.substr(6);
var currentTime = new Date(parseInt(dateString));
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
if (month.toString().length == 1)
month = "0" + month.toString();
if (day.toString().length == 1){
day = "0" + currentTime.getDate();}
var datenew = day + "/" + month + "/" + year;
var Date = new Date(Tue Jun 15 2021 23:52:47 GMT+0800 (Malaysia Time)).toDateString(); console.log(Date);
Result == Tue Jun 15 2021

Categories