I'm trying to create a countdown based on the lottery drawing times.
If the current date time is greater than the current weeks Wednesday then we display the current week Saturday's date time.
If the current date time is greater than the current weeks Saturday then we display the next Wednesday date time.
I don't want it to display for the last hour of that day.
I'm using moment and moment timezone.
var current = new Date(moment().tz('America/New_York').format('YYYY-MM-DDTHH:mm:ss'));
var wednesday = new Date().wednesday(); //if we are past the current Wednesday, it returns next weeks Wednesday
var wednesdayLimit = new Date(wednesday.getFullYear(), wednesday.getMonth(), wednesday.getDate(), 22, 59, 00);
var saturday = new Date().saturday();
var saturdayLimit = new Date(saturday.getFullYear(), saturday.getMonth(), saturday.getDate(), 22, 59, 00);
if (current > wednesdayLimit && current < saturdayLimit)
{
var temp = moment(saturdayLimit).format('YYYY-MM-DD HH:mm');
$('.countdown').data('date', temp);
$(".countdown").TimeCircles();
}
else if (current > saturdayLimit && current < wenesdayLimit)
{
var temp = moment(wednesdayLimit).format('YYYY-MM-DD HH:mm');
$('.countdown').data('date', temp);
$(".countdown").TimeCircles();
}
Maybe i'm over complicating it.
https://jsfiddle.net/1bLj4m2t/11/
UPDATE
Sorry, let me try to clarify. The countdown should not display between 22:59:01 - 23:59:59 on Wed or Sat. The last 1 hour and 1 minute of the day. This is why I created the *Limit vars and adjusted them to 22:59:00.
So to display the wednesdayLimit the current date time would need to be between
Thursdays 00:00:00 and Saturday 22:59:00
now to display saturdayLimit the current date time would need to be between
Sunday 00:00:00 and Wednesday 22:59:00
UPDATE 2
https://jsfiddle.net/1bLj4m2t/11/
Currently working but might be a cleaner/better way to do this?
I guess you just need to check which date is near to today? Is it Wednesday or Saturday? In other words check if Saturday is greater than Wednesday or vice versa. (Or find out which is minimum of the two)
Here is updated fiddle: https://jsfiddle.net/vnathalye/1bLj4m2t/6/
var current = new Date(moment().tz('America/New_York').format('YYYY-MM-DDTHH:mm:ss'));
var wednesday = new Date().wednesday();
var saturday = new Date().saturday();
$('.current').html(current);
$('.wednesday').html(wednesday);
$('.saturday').html(saturday);
var currentWeekday = moment(current).weekday();
var wednesdayWeekday = moment(wednesday).weekday();
var saturdayWeekday = moment(saturday).weekday();
var temp = (currentWeekday == wednesdayWeekday || currentWeekday == saturdayWeekday)? current : Math.min(wednesday, saturday);
$('.countdown').html(moment(temp).fromNow()); // use appropriate time of temp date
UPDATE: Added logic to check if current day is wednesday / saturday.
UPDATE 2: I've checked your updated fiddle and noticed that you are using momentjs & datejs. Do you really need 2 libraries? I'll stick to momentjs.
Looking at different values of current and the expected result that you have mentioned in your fiddle v11 I've updated my code # https://jsfiddle.net/vnathalye/1bLj4m2t/14/
//var current = moment('2016/01/17 08:00:00', 'YYYY/MM/DD HH:mm:ss'); //display Wed
//var current = moment('2016/01/20 00:00:00', 'YYYY/MM/DD HH:mm:ss'); //display Wed
//var current = moment('2016/01/20 22:59:00', 'YYYY/MM/DD HH:mm:ss'); //display Wed last hour
//var current = moment('2016/01/20 23:59:59', 'YYYY/MM/DD HH:mm:ss'); //display Wed last hour
//var current = moment('2016/01/21 00:00:00', 'YYYY/MM/DD HH:mm:ss'); //display Sat
//var current = moment('2016/01/23 00:00:00', 'YYYY/MM/DD HH:mm:ss'); //display Sat
var current = moment('2016/01/23 22:59:01', 'YYYY/MM/DD HH:mm:ss'); //display Sat last hour
var wednesday = moment(current).day(3); // sun=0 ... sat=6
var saturday = moment(current).day(6);
var currentWeekday = current.weekday();
var wednesdayWeekday = wednesday.weekday();
//var saturdayWeekday = moment(saturday).weekday();
var showWednesday = currentWeekday <= wednesdayWeekday;
var temp = showWednesday? wednesday : saturday;
temp = temp.hours(23).minutes(59).seconds(59).milliseconds(999);
$('.current').html(current.toDate());
$('.wednesday').html(wednesday.toDate());
$('.saturday').html(saturday.toDate());
$('.countdown').html((showWednesday? "Wed" : "Sat") +
(temp.diff(current, "minutes") <= 60 ? " last hour" : ""));
Note:
.day() function returns the day of current week (unlike wednesday()/saturday() that you are using). This allows me to simply compare weekday of current with weekday of wednesday to decide whether to use wednesday or saturday for further calculations
To check if its the last hour of temp(wednesday/saturday), you just check the difference is <= 60 minutes
I've used the date strings as you have used in your example and hence used the second param 'YYYY/MM/DD HH:mm:ss' while calling moment(). Ref: https://github.com/moment/moment/issues/1407 to know recommended ways of using moment()
While displaying the date I've used .toDate() but you can use .format()
Related
I am trying to get previous week data ..
Suppose I am in current week whether start or end I have to get value of previous week.
Suppose today is 7 Nov Monday.
But I have to get value of Last Sunday 30 Oct (00:00) to 5th Nov Saturday (23:59:59)
So, start date would be 30 oct and end date would be 5th Nov
And tomorrow will be 8 Nov Tuesday but then also
I have to get value of Last Sunday 30 Oct (00:00) and 5th Nov Saturday (23:59:59)
start date would be 31 oct and end date would be 5th Nov,
and it should be dynamic, if week change then again previous week of current week.
I am using below code but from this I am getting current week start and end weekdays
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();
var last = first + 6;
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
You can move the var first to 7 days before then you will get the previous week's first day and last day.
Try out this code.
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();
first = first - 7
var firstdayOb = new Date(curr.setDate(first));
var firstday = firstdayOb.toUTCString();
var firstdayTemp = firstdayOb;
var lastday = new Date(firstdayTemp.setDate(firstdayTemp.getDate() + 6 )).toUTCString();
console.log(firstday);
console.log(lastday);
I am trying to get the date range of the past Wednesday to past Tuesday(7 days) from today's date.
Say the current date is 2022-05-01(May 1st), I am expecting the result to be the past Tuesday(end date) to Past Wednesday (start date = Past Tuesday -7 days)
i.e 20 April 2022 to 26 April 2022
function getStartAndEndDates () {
var now = new Date('2022-05-01'); //May 1st 2022
var day = now.getDay();
var diff = (day <= 2) ? (7 - 2 + day ) : (day - 2);
var PastTuesday = new Date();
var PastWednesday = new Date(PastTuesday.setDate(now.getDate() - diff));
console.log('End date is', PastTuesday.toISOString());
PastWednesday.setDate(PastTuesday.getDate() - 6);
console.log('Start Date is',PastWednesday.toISOString());
return[PastWednesday,PastTuesday];
}
Output obtained is:
End date is 2022-03-27T19:25:35.726Z //here month is set to March
Start Date is 2022-03-21T19:25:35.726Z
Expected Result is
End date is 2022-04-26T19:25:35.726Z // month is supposed to be April
Start Date is 2022-04-20T19:25:35.726Z
How can I change the code to get the expected result?
You should do something like
function getLastWeek(date) {
var today = new Date(date);
var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
return lastWeek;
}
// Your DATE
date = '2022-05-01'
//
var lastWeek = getLastWeek(date);
var lastWeekMonth = lastWeek.getMonth() + 1;
var lastWeekDay = lastWeek.getDate();
var lastWeekYear = lastWeek.getFullYear();
var lastWeekDisplay = lastWeekMonth + "/" + lastWeekDay + "/" + lastWeekYear;
console.log(lastWeekDisplay);
In your code:
var now = new Date('2022-05-01'); //May 1st 2022
Dates in the format YYYY-MM-DD are parsed as UTC, so the above will create a date object representing 2022-05-01T00:00:00Z.
var day = now.getDay();
This will return the local day number. For users with a zero or positive offset, it will return 0 (Sunday) but for users with a negative offset, it will return 6 (Saturday) because their local date is still the previous day.
var diff = (day <= 2) ? (7 - 2 + day ) : (day - 2);
Given day is 0 (for me), the above sets diff to 5.
var PastTuesday = new Date();
This creates a date for "now", which for me is 17 April.
var PastWednesday = new Date(PastTuesday.setDate(now.getDate() - diff));
In the above, now.getDate returns 1, and 1 - 5 is -4, so it sets the date for PastTuesday to -4. Now PastTuesday is in April, so it is set to 4 days prior to the start of April, i.e. 27 March.
Note that this adjusts PastTuesday and creates a copy for PastWednesday at the same time.
console.log('End date is', PastTuesday.toISOString());
Shows the equivalent UTC date and time, with the time representing the time that the code was run.
PastWednesday.setDate(PastTuesday.getDate() - 6);
Sets PastWednesday to 6 days prior to PastTuesday.
Anyhow, what is required is to do everything either as UTC or local, don't mix the two.
Sticking to code as closely as possible to the original and assuming a timestamp in YYYY-MM-DD format is parsed to the function, consider the following, which does everything as local:
// Parse timestamp in YYYY-MM-DD format as local
function parseISOLocal(s = new Date().toLocaleDateString('en-CA')) {
let [y, m, d] = s.split(/\D/);
return new Date(y, m-1, d);
}
// Get week Wed to Tue prior to passed date
function getStartAndEndDates (date) {
// Parse timestamp as local
var pastTuesday = parseISOLocal(date);
// Adjust pastTuesday to previous Tuesday
var day = pastTuesday.getDay();
var diff = (day <= 2) ? (7 - 2 + day ) : (day - 2);
var pastWednesday = new Date(pastTuesday.setDate(pastTuesday.getDate() - diff));
console.log('End date is', pastTuesday.toDateString());
// Adjust pastWednesday to previous Wednesday
pastWednesday.setDate(pastTuesday.getDate() - 6);
console.log('Start Date is',pastWednesday.toDateString());
return [pastWednesday, pastTuesday];
}
// Sunday 1 May 2022
console.log(getStartAndEndDates('2022-05-01').map(d => d.toDateString()));
// Current date
console.log(getStartAndEndDates().map(d => d.toDateString()));
I'm using a delivery Day counter to show my customers on which day they can expect their package.
But... there is a problem.
The delivery days should be (the day ordered + 2 days (before 12 o clock(germany)) if not 3 days)that's working like a charme. But I can't get my head aroung excluding sundays. At the moment the counter adds one day if it is sunday... But for example if it is saturday the counter doesn't add a day (for the nonDeliveryDate)
atm (after 12 o' clock):
17.09.2020 - delivery to Monday = right
18.09.2020 - delivery to Monday = wrong (should be Tuesday)
19.09.2020 - delivery to Tuesday = wrong (should be Wednesday)
20.09.2020 - delivery to Wednesday = right
I think the problem is that the counter only adds one day if "today" is sunday but not if one of the next 3 days is sunday... but i'm not really sure how to solve that.
That's my script:
<script type='text/javascript'>
jQuery(function($) {
// Current date/time
var now = new Date();
// Placeholder for delivery time
var deliveryDate;
// Amount of days to deliver
var deliveryDays = 2;
// Working hours (in UTC -1)
var workingHours = [0 , 9];
// Non-delivery days/dates
// Must match the format returned by .toString():
// Mon Sep 28 1998 14:36:22 GMT-0700 (Pacific Daylight Time)
var nonDelivery = [
"Sun",
"Dec 24",
"Dec 25",
"Dec 31",
"Jan 1"
];
// Create a regular expression
var rxp = new RegExp(nonDelivery.join("|"));
// addDay holds the amount of days to add to delivery date
var addDay = deliveryDays;
// Add an extra day if outside of working hours
var currentHour = now.getUTCHours();
if (currentHour < workingHours[0] ||
currentHour > workingHours[1]) {
addDay++;
}
// Create our delivery date
while (!deliveryDate) {
// Add day(s) to delivery date
now.setDate(
now.getDate() + addDay
);
deliveryDate = now;
if (rxp.test(deliveryDate)) {
addDay = 1;
deliveryDate = false;
}
}
// Format
var locale = "de-DE"; // Our locale
// var day = deliveryDate.toLocaleDateString(locale, { day: "numeric" });
var weekday = deliveryDate.toLocaleDateString(locale, { weekday: "long" });
$('#countdownDate').html( weekday + " " );
});
</script>
Hopefully someone can help me with that...
Thanks a lot!
I'm trying to convert the string 'Wed, 11:45 pm' into a proper datetime (preferably UTC). Is it possible to do without needing the month? The proper datetime would be the upcoming Wednesday. It's Monday(23rd) today, so Wednesday would be the 25th.
const time = 'Wed, 11:45 pm'
const datetime = moment(time).utc() // yields 2019-09-23T05:00:00Z (todays date)
I need it to yield 2019-09-25T22:25:58Z (two days, wednesday, from now)
I think your question has to be split to a few steps and your requirement is not very clear.
The steps I did here is
Split your input to 'Wed' and '11:45 pm'.
Use 'Wed' to calculate the coming Wednesday (If today is wednesday then coming wednesday would still be today or the next wednesday)
Set 11:45 to the hour and minute.
Change it to the format you prefer.
I saw your tag has cypress so I wrote a cypress test with the function above.
describe('Find the coming Wednesday', () => {
it('test',()=>{
cy.visit('https://www.google.com');
const time = "Wed, 11:45 pm";
var returnedDatetime = findComingDate(time);
const outputDatetime = Cypress.moment(returnedDatetime).utc().format();
console.log(outputDatetime);
})
})
function findComingDate(dayAndTime) {
//split your string
var dayAndTime = dayAndTime.split(',');
var day = dayAndTime[0];
var time = dayAndTime[1];
var parts = time.match(/(\d+):(\d+) (am|pm)/);
if (parts) {
var hours = parseInt(parts[1]),
minutes = parseInt(parts[2]),
tt = parts[3];
}
if (tt === 'pm' && hours < 12) hours += 12;
var days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
var dayindex = days.indexOf(day) + 1;
if (dayindex === 0) {
throw ('You can only input 3 letters for the day name')
}
else {
var cd = new Date();
//use commented code below if today is tuesady and your input is tuesday and you want output is today.
cd.setDate(cd.getDate() + ((7-cd.getDay())%7+dayindex)%7);
//use commented code below if today is tuesady and your input is tuesday and you want output is next tuesday.
//cd.setDate(cd.getDate() + (7-cd.getDay())%7+dayindex)
//change the time
cd.setHours(hours,minutes,0,0);
return cd;
}
}
I tested it on 2019-9-24 with your input 'Wed, 11:45 pm' it returns UTC time
2019-09-24T11:45:00Z
Try
moment('Wed, 11:45 pm', 'ddd HH:mm a')
Is this due to the time zones settings on my laptop or is it something more complex?
Current time
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var week = 7;
console.log ('date ',dateObj,' day is ',day);
output
> date Mon Jan 14 2019 23:05:35 GMT-0500 (Eastern Standard Time) day is 15
edit: that the time that new Date() created (Mon Jan 14 2019 23:05:35 GMT-0500) is in fact the correct time I am after.
after considering the information I read in comments, it seems I need to subtract the hourly change ( - 5 ) to get the EST, which seems to be what I'm after.
it seems I need to subtract the hourly change ( - 5 ) to get the EST
Subtracting 5 is not a good idea, as it doesn't account for daylight savings.
I'd suggest using toLocaleString() to be safe.
var dateObj = new Date();
//Output as UTC
var utc = { timeZone: "UTC" };
console.log(dateObj.toLocaleString("en-US", utc));
//Output as EST
var est = { timeZone: "America/New_York" };
console.log(dateObj.toLocaleString("en-US", est));
You need to keep timezones consistent. Change this:
console.log ('date ',dateObj,' day is ',day);
To this:
console.log ('date ',dateObj.getUTCDate(),' day is ',day);
And it will work:
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var week = 7;
console.log('date ', dateObj.getUTCDate(), ' day is ', day);