Get timestamp of week returns NaN - javascript

I am trying to get a timestamp of the week, starting on a monday, similar to this C# script:
DateTime now = DateTime.UtcNow;
now = DateTime.UtcNow.StartOfWeek(DayOfWeek.Monday);
int weekday = (int)(now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
This returns: 1548633600
When trying this in javascript I get NaN error:
var d = new Date();
var w = Date.UTC(thisYear, thisMonth, d.setDate(d.getDate() - (d.getDay() || 7) + 1), 0, 0, 0, 0);
var weekDay = Math.floor(w / 1000);
Not sure what i am doing wrong. Hoping for help :-)

var d = new Date();
var day = d.getUTCDay();
var utcTime = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() - day + 1);
var weekDay = utcTime / 1000;
console.log(weekDay);

Try this way: this returns Friday, update it to get Monday
var t = new Date().getDate() + (6 - new Date().getDay() - 1) - 7 ;
var d = new Date();
d.setDate(t);
var lastFriday = d;
console.log(lastFriday);

Related

days left until user's bday

I've created a pirate speak program.
It asks the user for their name and date of birth and calculates the years from the input and added 100 years for fun. I also need to calculate the number of days left until their birthday using user input but I don't know what to do. I've tried some methods and stuff but its not working. any tips or mistakes I need to fix?
var name = prompt('What\'s yer name?');
var date = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
let years = date;
let num = years.substring(6, 10);
var myInput = parseInt(num);
var x = myInput;
var y = 100;
var result = x + y;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
var myInput = parseInt(date);
var bday = myInput;
function daysUntilNext(month, day){
var tday= new Date(), y= tday.getFullYear(), next= new Date(y, month-1, day);
tday.setHours(0, 0, 0, 0);
if(tday>next) next.setFullYear(y+1);
return Math.round((next-tday)/8.64e7);
}
var d= daysUntilNext(date);
console.log(d+' day'+(d>1? 's': '')+' until yer birthday');
Ok, I have cleaned up your JavaScript a little. Best practice was to get the date from the string and parse each part then just create a Date object from there. What's easier in the future is to use a datepicker HTML component rather than a string, but I understand that wasn't your goal for this.
Next, do the plus 100 calculation and display that result.
Lastly, take the Date object we made and take the information that we need from it. FWIW getDay() returns the day of the week, you want getDate() which return the day of the month. Then calculate how many days away from those in the next year. Display that result in the console.
I think you were getting that NAN because you were doing calculations on strings not numbers or it was because there weren't enough parameters in daysUntilNext(), so you were operating on null or undefined somewhere
var name = prompt('What\'s yer name?');
var birthDateString = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
var daySubstring = birthDateString.substring(3, 5);
var monthSubstring = birthDateString.substring(0, 2);
var yearSubstring = birthDateString.substring(6, 10);
var birthdate = new Date(parseInt(yearSubstring), parseInt(monthSubstring) - 1, parseInt(daySubstring));
var ONE_HUNDRED = 100;
var result = parseInt(yearSubstring) + ONE_HUNDRED;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
function daysUntilNext(month, day) {
var today = new Date();
var year = today.getFullYear();
var next = new Date(year, month, day);
today.setHours(0, 0, 0, 0);
if (today > next) next.setFullYear(year + 1);
return Math.round((next - today) / 8.64e7);
}
var d = daysUntilNext(birthdate.getMonth(), birthdate.getDate());
console.log(d + ' day' + (d > 1 ? 's' : '') + ' until yer birthday');
The other answerer's code is correct, but not clear. Here's the same, only more user-friendly.
The difference is that single-digit months or days won't bother you.
I hope I could help.
var name = prompt('What\'s yer name?');
var birthDateString = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
var inputdate = birthDateString.split("/");
var daySubstring = inputdate[1];
var monthSubstring = inputdate[0];
var yearSubstring = inputdate[2];
var birthdate = new Date(parseInt(yearSubstring), parseInt(monthSubstring) - 1, parseInt(daySubstring));
var ONE_HUNDRED = 100;
var result = parseInt(yearSubstring) + ONE_HUNDRED;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
function daysUntilNext(month, day) {
var today = new Date();
var year = today.getFullYear();
var next = new Date(year, month, day);
today.setHours(0, 0, 0, 0);
if (today > next) next.setFullYear(year + 1);
return Math.round((next - today) / 8.64e7);
}
var d = daysUntilNext(birthdate.getMonth(), birthdate.getDate());
console.log(d + ' day' + (d > 1 ? 's' : '') + ' until yer birthday');

Get the number of weeks between a start date and end date using js

As the title says I want to calculate the number of weeks between a start date and end date I'm a bit confuse can someone shed some light on me.
var start_date = new Date();
var end_date = new Date(2018,09,30);
use moment.js.
var start_date = new Date();
var end_date = new Date(2018,09,30);
change to format
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now, "DD/MM/YYYY HH:mm:ss").diff(moment(then, "DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
you can get total no of days, you can divide/7. so that you can get no of weeks.
function diff_weeks(dt2, dt1)
{
var diff =(dt2.getTime() - dt1.getTime()) / 1000;
diff /= (60 * 60 * 24 * 7);
return Math.abs(Math.round(diff));
}
dt1 = new Date(2018,09,25);
dt2 = new Date(2018,10,02);
alert(diff_weeks(dt1, dt2));
dt1 = new Date("September 25, 2018 08:11:00");
dt2 = new Date("October 02, 2018 08:11:00");
alert(diff_weeks(dt1, dt2));
this function will give you the difference in weeks
Try this code and number of weeks will be shown in dateArr also you will see here every week start- end. You can edit code for your needs.
var start = new Date(Date.UTC(2016, 09, 30, 0, 0, 0));
var end = new Date(Date.UTC(2016, 11, 02, 0, 0, 0));
var sDate;
var eDate;
var dateArr = [];
while(start <= end){
if (start.getDay() == 1 || (dateArr.length == 0 && !sDate)){
sDate = new Date(start.getTime());
}
if ((sDate && start.getDay() == 0) || start.getTime() == end.getTime()){
eDate = new Date(start.getTime());
}
if(sDate && eDate){
dateArr.push({'startDate': sDate, 'endDate': eDate});
sDate = undefined;
eDate = undefined;
}
start.setDate(start.getDate() + 1);
}
console.log(dateArr);
There are some really cool JavaScript libraries you can use for this. A nice lightweight one would be date-fns. I’ve linked the download link and I’ve written some example code for you from their documentation:
Download it/add it to your packages: https://date-fns.org
Documentation: https://date-fns.org/v1.29.0/docs/differenceInWeeks
Example:
// How many full weeks are between 5 July
// 2014 and 20 July 2014?
var result = differenceInWeeks(
new Date(2014, 6, 20),
new Date(2014, 6, 5)
)
//=> 2

How to get days between date range by using javascript or jquery

In a form, I define a start date, an end date, and weekdays
Example:
Start date: 2017-02-07
End date: 2017-03-07
Weekdays: Monday and Thursday
Now I want to get all Mondays and Thursdays between start date and end date by using Javascript or jQuery.
Who can help me?
Thanks...
Simple code. Codepen
var startDate = new Date('2017-02-07');
var endDate = new Date('2017-02-17');
var monday = [];
var thursday = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
if(d.getDay()==1)
monday.push(d);
else if(d.getDay()==4)
thursday.push(d);
}
You can parse date and iterate over increment 1 day and getDay to map with sun(0) to sat(6)
var startDate = new Date("2017-02-07");
var endDate = new Date("2017-03-07");
var totalMon = [];
var totalThu = [];
for (var i = startDate; i <= endDate; ){
if (i.getDay() == 1){
totalMon.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
if (i.getDay() == 4){
totalThu.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
i.setTime(i.getTime() + 1000*60*60*24);
}
console.log(totalMon.length ,totalMon);
console.log(totalThu.length ,totalThu);
Below code finds number of Mondays. You can modify it to calculate any day. It basically finds the difference of days in two dates. Divide it by 7 (this is the number of times everyday will come). Now for pending days loop through the dates and check if a desired day comes in this loop.
var startDate = new Date(2017, 02, 07);
var endDate = new Date(2017, 03, 07);
var dayDiff = Math.round((endDate-startDate)/(1000*60*60*24));
var numberOfMondays = Math.floor(dayDiff/7);
var remainingDays = dayDiff%7;
for(i=0;i<remainingDays;i++)
{
var dateObj = new Date();
dateObj.setDate(endDate.getDate() - i);
if(dateObj.getDay() == 2)
numberOfMondays=numberOfMondays+1;
}
alert(numberOfMondays);
PS : the other two answer are looping through all the dates. I will not suggest this. In code above the number of iterations in loop will never exceed 6 irrespective of the difference in dates.

How to add one month to a date here?

I have two date variables. The first one defaults to last friday. Based on this date I'm trying to add a month to it. When I try the following code, it does not seem to work.
var StartDate = new Date()
var DayOfWeek = 5;//friday
StartDate.setDate(StartDate.getDate() + (dayOfWeek - 7 - StartDate.getDay()) % 7);
This does not seem to work.
var EndDate = new Date(StartDate)
EndDate.setDate(EndDate.getMonth() + 7)
The reason it isn't working is you have to set the month not the date.
Change your end date code to be:
var EndDate = new Date(StarteDate);
var x = 1;
EndDate.setMonth(EndDate.getMonth() + x);
Here's a reference on setMonth http://www.w3schools.com/jsref/jsref_setmonth.asp
You can add a month by doing this:
In general:
var b = new Date();
var a = new Date(new Date().setMonth(b.getMonth()+1)); //<< this line
alert(a);
Your code:
var StartDate = new Date();
var dayOfWeek = 5;
StartDate.setDate(StartDate.getDate() + (dayOfWeek + 7 - StartDate.getDay()) % 7);
var EndDate = new Date(StartDate)
EndDate.setMonth(EndDate.getMonth() + 1);
alert(EndDate); //remove...
JS Fiddle DEMO with your code

Get last week date with jQuery/Javascript

I'm trying to get the last week date in JavaScript, without the time.
So for example, 10-02-2012, instead of 10-02-12 13:34:56 GMT.
Is there an easy solution out there for this?
Thank you!
Edit:
I'm trying to make this dynamic, so that the resulting variable is always one week before the current date. Here's what I've done to calculate the today variable, if this helps or can be used!
var currentTime = new Date();
var month = currentTime.getMonth() + 1
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var today = month + "-" + day + "-" + year;
alert(today)
I prefer something like this
​
function getLastWeek() {
var today = new Date();
var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
return lastWeek;
}
var lastWeek = getLastWeek();
var lastWeekMonth = lastWeek.getMonth() + 1;
var lastWeekDay = lastWeek.getDate();
var lastWeekYear = lastWeek.getFullYear();
var lastWeekDisplay = lastWeekMonth + "/" + lastWeekDay + "/" + lastWeekYear;
var lastWeekDisplayPadded = ("00" + lastWeekMonth.toString()).slice(-2) + "/" + ("00" + lastWeekDay.toString()).slice(-2) + "/" + ("0000" + lastWeekYear.toString()).slice(-4);
console.log(lastWeekDisplay);
console.log(lastWeekDisplayPadded);
And if you're using jQuery UI, you can do this instead of the manual steps to build the string
var lastWeekDisplay = $.datepicker.formatDate('mm/dd/yy', getLastWeek());
Or for today
var todayDisplay = $.datepicker.formatDate('mm/dd/yy', new Date());
var firstDay = new Date("2009/10/02");
var previousweek= new Date(firstDay.getTime() - 7 * 24 * 60 * 60 * 1000);
Check out this link. It will help:- http://code.google.com/p/datejs/
We can't have a javascript date question answered without mentioning Moment.js.
moment().subtract('days', 7).format('MM-DD-YYYY')
Possible without external dependencies
new Date().setDate(new Date().getDate() - 7)
If you really want to create this from a full timestamp like 10-02-12 13:34:56 GMT, you might want to do this:
var time = '10-02-12 13:34:56 GMT';
document.write(time.substr(0,7));
use this code to subtract any number of days as i have selected 9 it will give last 10 days result including today
var date = new Date();
var day=date.getDate();
var month=date.getMonth() + 1;
var year=date.getFullYear();
var startDate=day+"/"+month+"/"+year;
var dayBeforeNineDays=moment().subtract(9, 'days').format('DD/MM/YYYY');
startDate=dayBeforeNineDays;
var endDate=day+"/"+month+"/"+year;
function getLastWeek() {
let today = new Date();
let day = today.getDay();
let t = day-1;
let monday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - t - 7); //monday from last week
let sunday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - t - 1); //sunday from ast week
return [monday, sunday];
}
var last_week = getLastWeek();

Categories

Resources