Moment convert day str into moment with only the day and time - javascript

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')

Related

A delivery counter which excludes sunday and holidays

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!

Why can't I display JUST the date (date, month, and year without time)?

I have some code, that is doing pretty much all i need it to do. Its calculating 3 days in the future, excluding dates, and then displaying my "estimated dispatch date"
The date, however displays in full date and time, instead of just date.
Day Month Date Year 12:02:57 GMT+0100 (British Summer Time)
Can anyone help with the code below, so that it excludes local time and only displays the future date, excluding weekend, DD/MM/YYYY or, in the below format;
Monday 20th June
Thanks in advance!
function addDates(startDate,noOfDaysToAdd){
var count = 0;
while(count < noOfDaysToAdd){
endDate = new Date(startDate.setDate(startDate.getDate() + 1));
if(endDate.getDay() != 0 && endDate.getDay() != 6){
//Date.getDay() gives weekday starting from 0(Sunday) to 6(Saturday)
count++;
}
}
return startDate;
}
var today = new Date();
var daysToAdd = 3;
document.write ('Estimated Dispatch Date: ' + addDates(today,daysToAdd));
You can use the toDateString method to display just the date portion of your Date object, but you will need to use a few other methods for full control over the format of your date string...
You can display just the date, month and year parts of your local date and time with a few extra lines of code using the getDate, getMonth, and getFullYear methods to help with the formatting. You could try passing specific formatting parameters to toLocaleString, but this may display different results in different browsers. For example, the code below outputs a date in the format dd/mm/yyyy in Chrome but that output is not guaranteed across browsers.
new Date().toLocaleString('en-GB', {year: 'numeric', month: 'numeric', day: 'numeric'})
Not sure I am following how you want to handle weekend dates, so the below handles the date formatting that you want in the formatDate function separately from the addDays function where it just handles weekend dates by rolling the date forward to a Monday if the initially calculated date lands on a Saturday or Sunday.
// format input date to dd/mm/yyyy
const formatDate = (date) => {
const d = date.getDate(); // day of the month
const m = date.getMonth(); // month index from 0 (Jan) to 11 (Dec)
const yyyy = date.getFullYear(); // 4 digit year
const dd = (d < 10 ? '0' : '') + d; // format date to 2 digit
const mm = (m + 1 < 10 ? '0' : '') + (m + 1); // convert index to month and format 2 digit
return `${dd}/${mm}/${yyyy}`;
};
// add input days to today and adjust for weekend output
const addDays = (today, days) => {
const now = today.getTime() // now in UTC milliseconds
const ms = 24 * 60 * 60000; // milliseconds in one day
const date = new Date((days * ms) + now); // today plus input days
const day = date.getDay(); // weekday index from 0 (Sun) to 6 (Sat)
// adjust weekend results to next weekday
if (day === 0 || day === 6) {
let adj = day === 0 ? 1 : 2;
return new Date(((days + adj) * ms) + now);
}
return date;
};
document.write('Estimated Dispatch Date: ' + formatDate(addDays(new Date(), 3)));

DateTime calculation issue

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()

How do I roll a date forward to a specified day in Javascript?

I'm working on a form that needs to automatically calculate the day the form is being submitted in the format ('MMDDYYYY'), and then on the click of one of two links a link, calculate the closest first day of the coming month, and the closest 15th day of the coming month.
I already created a script that pulls in the date and outputs it to a variable in the format I need, but I need help in calculating the roll forward.
Here's an example of the logic I'm thinking I need:
If the current date is 04092013, on a the button press labeled "Coming 1st of Month" a variable value of 05012013 would be calculated.
If the current date is 04092013, on a button press labeled "Coming 15th of Month" a variable value of 04152013 would be calculated.
If the current date is 04162013 or any date up to the end of the current month, on a button press labeled "Coming 15th of Month" a variable value of 05152013 would be calculated.
Look at the Date object, it should provide what you need:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
For example something like this for your first 2 buttons:
$(function() {
var date = new Date(2013, 10, 24);
$("#date").html(date.toString());
$("#date1").html((new Date(date.getYear(), date.getMonth()+1, 1)).toString());
$("#date2").html((new Date(date.getYear(), date.getMonth()+1, 15)).toString());
});
(Though I'm sure there are easier ways to do this if you look through the Date documenation)
Here is an example. If you want it back as a string, you'll have to format it at the end as desired (work with UTC ).
If you put in a date that has the same day number as you're asking of it, it returns the same day, not moving forwards a month.
var date_string = '04092013';
// MMDDYYYY
function nextNthOfMonth(date_string, n) {
var date;
// n to Int, default 1
n = (+n || 1);
// date_string to ISO 8601
date_string = // "yyyy-MM-ddTHH:mm:ssZ"
date_string.slice(4)
+ '-' + date_string.slice(0, 2)
+ '-' + date_string.slice(2, 4)
+ 'T00:00:00Z';
// construct date object
date = new Date(date_string);
// fix to desired date
if (n < date.getUTCDate()) { // adjust for month if req.
date.setUTCMonth(date.getUTCMonth() + 1);
}
date.setUTCDate(n);
return date; // or format as desired
}
nextNthOfMonth(date_string, 1);
// Wed May 01 2013 01:00:00 GMT+0100 (GMT Daylight Time)
nextNthOfMonth(date_string, 15);
// Mon Apr 15 2013 01:00:00 GMT+0100 (GMT Daylight Time)
Since you know the format of your date, split the input into parts:
var dateStr = '04092013'
var month = dateStr.substr(0,2);
var day = dateStr.substr(2,2);
var year = dateStr.substr(4,4);
The construct a new date base on the rule you want to set:
var newDate;
switch(rule)
{
case 'rule1':
newDate = new Date(year, month, 1);//first month is 0
break;
case 'rule2':
newDate = new Date(year, month, 15);//first month is 0
break;
}
remember to check if the day is greater that 15.
Try
function getDate() {
var s = document.getElementById('date').value;
if(s){
return new Date(s.substring(4), parseInt(s.substring(2, 4), 10) - 1, s.substring(0, 2))
}
}
function comingDate(date, day){
date = new Date(date);
var cday = date.getDate();
date.setDate(day);
if(cday >= day){
date.setMonth(date.getMonth() + 1)
}
return date
}
function f15(){
var d = getDate();
var next = comingDate(d, 15);
console.log(next)
}
function f1(){
var d = getDate();
var next = comingDate(d, 1);
console.log(next)
}
Demo: Fiddle

Converting milliseconds to a date (jQuery/JavaScript)

I'm a bit of a rambler, but I'll try to keep this clear -
I'm bored, so I'm working on a "shoutbox", and I'm a little confused over one thing. I want to get the time that a message is entered, and I want to make sure I'm getting the server time, or at least make sure I'm not getting the local time of the user. I know it doesn't matter, since this thing won't be used by anyone besides me, but I want to be thorough. I've looked around and tested a few things, and I think the only way to do this is to get the milliseconds since January 1, 1970 00:00:00 UTC, since that'd be the same for everyone.
I'm doing that like so:
var time = new Date();
var time = time.getTime();
That returns a number like 1294862756114.
Is there a way to convert 1294862756114 to a more readable date, like DD/MM/YYYY HH:MM:SS?
So, basically, I'm looking for JavaScript's equivalent of PHP's date(); function.
var time = new Date().getTime(); // get your number
var date = new Date(time); // create Date object
console.log(date.toString()); // result: Wed Jan 12 2011 12:42:46 GMT-0800 (PST)
If you want custom formatting for your date I offer a simple function for it:
var now = new Date;
console.log( now.customFormat( "#DD#/#MM#/#YYYY# #hh#:#mm#:#ss#" ) );
Here are the tokens supported:
token: description: example:
#YYYY# 4-digit year 1999
#YY# 2-digit year 99
#MMMM# full month name February
#MMM# 3-letter month name Feb
#MM# 2-digit month number 02
#M# month number 2
#DDDD# full weekday name Wednesday
#DDD# 3-letter weekday name Wed
#DD# 2-digit day number 09
#D# day number 9
#th# day ordinal suffix nd
#hhhh# 2-digit 24-based hour 17
#hhh# military/24-based hour 17
#hh# 2-digit hour 05
#h# hour 5
#mm# 2-digit minute 07
#m# minute 7
#ss# 2-digit second 09
#s# second 9
#ampm# "am" or "pm" pm
#AMPM# "AM" or "PM" PM
And here's the code:
//*** This code is copyright 2002-2016 by Gavin Kistner, !#phrogz.net
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
Date.prototype.customFormat = function(formatString){
var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhhh,hhh,hh,h,mm,m,ss,s,ampm,AMPM,dMod,th;
YY = ((YYYY=this.getFullYear())+"").slice(-2);
MM = (M=this.getMonth()+1)<10?('0'+M):M;
MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substring(0,3);
DD = (D=this.getDate())<10?('0'+D):D;
DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getDay()]).substring(0,3);
th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);
h=(hhh=this.getHours());
if (h==0) h=24;
if (h>12) h-=12;
hh = h<10?('0'+h):h;
hhhh = hhh<10?('0'+hhh):hhh;
AMPM=(ampm=hhh<12?'am':'pm').toUpperCase();
mm=(m=this.getMinutes())<10?('0'+m):m;
ss=(s=this.getSeconds())<10?('0'+s):s;
return formatString.replace("#hhhh#",hhhh).replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm).replace("#AMPM#",AMPM);
};
You can simply us the Datejs library in order to convert the date to your desired format.
I've run couples of test and it works.
Below is a snippet illustrating how you can achieve that:
var d = new Date(1469433907836);
d.toLocaleString(); // expected output: "7/25/2016, 1:35:07 PM"
d.toLocaleDateString(); // expected output: "7/25/2016"
d.toDateString(); // expected output: "Mon Jul 25 2016"
d.toTimeString(); // expected output: "13:35:07 GMT+0530 (India Standard Time)"
d.toLocaleTimeString(); // expected output: "1:35:07 PM"
Below is a snippet to enable you format the date to a desirable output:
var time = new Date();
var time = time.getTime();
var theyear = time.getFullYear();
var themonth = time.getMonth() + 1;
var thetoday = time.getDate();
document.write("The date is: ");
document.write(theyear + "/" + themonth + "/" + thetoday);
Try using this code:
var datetime = 1383066000000; // anything
var date = new Date(datetime);
var options = {
year: 'numeric', month: 'numeric', day: 'numeric',
};
var result = date.toLocaleDateString('en', options); // 10/29/2013
See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
Try using this code:
var milisegundos = parseInt(data.replace("/Date(", "").replace(")/", ""));
var newDate = new Date(milisegundos).toLocaleDateString("en-UE");
Enjoy it!
so you need to pass that var time after getTime() into another new Date()
here is my example:
var time = new Date()
var time = time.getTime()
var newTime = new Date(time)
console.log(newTime)
//Wed Oct 20 2021 15:21:12 GMT+0530 (India Standard Time)
here output is my datetime standard format for you it will be in country format
if you want it in another format then you can apply another date function on var newTime
like
var newTime = new Date(time).toDateString()
console.log(newTime)
//Wed Oct 20 2021
Try this one :
var time = new Date().toJSON();
One line code.
var date = new Date(new Date().getTime());
or
var date = new Date(1584120305684);
/Date(1383066000000)/
function convertDate(data) {
var getdate = parseInt(data.replace("/Date(", "").replace(")/", ""));
var ConvDate= new Date(getdate);
return ConvDate.getDate() + "/" + ConvDate.getMonth() + "/" + ConvDate.getFullYear();
}
Assume the date as milliseconds date is 1526813885836, so you can access the date as string with this sample code:
console.log(new Date(1526813885836).toString());
For clearness see below code:
const theTime = new Date(1526813885836);
console.log(theTime.toString());
use datejs
new Date().toString('yyyy-MM-d-h-mm-ss');

Categories