How to write a conditional for a time? - javascript

I'm trying to get a conditional what with the date of tomorrow example let me know what if is tomorrow and is more than 1pm of tomorrow so do something.
I work with MomentJs, so if you have a solution with this that can help me, is appreciated.

To get a Date for 13:00 tomorrow, you can create a date for today, add a day, then set the time to 13:00.
Then you can directly compare it to other dates using comparison operators < and > (but you need to convert both dates to numbers to compare as == or ===).
E.g.
// return true if d0 is before d1, otherwise false
function isBefore(d0, d1) {
return d0 < d1;
}
// Generate some sample dates
let now = new Date();
let d0 = new Date(now.setDate(now.getDate() + 1));
let d1 = new Date(now.setHours(10));
let d2 = new Date(now.setHours(15));
// Format output
function formatDate(d) {
let options = {day:'2-digit', month:'short', year:'numeric', 'hour-12':false, hour:'2-digit',minute:'2-digit'};
return d.toLocaleString('en-gb',options);
}
// Create a test date for 13:00 tomorrow
var testDate = new Date();
testDate.setDate(testDate.getDate() + 1);
testDate.setHours(13,0,0,0);
// Test it against sample dates
[d0,d1,d2].forEach(function(d) {
console.log(formatDate(d) + ' before ' + formatDate(testDate) + '? ' + isBefore(d, testDate));
})

In momentJS, you can get tomorrow by
const tomorrow = moment().add(1, 'days');
If you want to get tomorrow 1.00 PM then
var tomorrow = moment('01:00 pm', "HH:mm a").add(1, 'days');
If you want to compare, then
var tomorrow = moment('01:00 pm', "HH:mm a").add(1, 'days');
var current = moment();
if(current < tomorrow)
console.log('true');
else
console.log('false');

Related

How do I get the days between the today's day and the last day of the month using Moment.js?

Here's the code that I have right now:
const moment = require('moment')
const m = moment
const currDay = m().format('D')
const dayOfWeek = m().format('dddd')
const daysInMonth = m().daysInMonth()
const startOfMonth = moment().startOf('month').format('YYYY-MM-DD hh:mm');
const endOfMonth = moment().endOf('month').format('YYYY-MM-DD hh:mm');
I need to create a calendar row where the first item would be the todays date, and the rest of the calendar items would be the whatever amount of days are left depending on the current month so I could render each day in between in my HTML with Vue.
Example: Wed 8, Thu 9, Fri 10 ... Fri 31.
I think the OP is tripped up on the common mistake of formatting prematurely. format is good to see an intermediate result, but doing so produces a string that's no good for additional calculation.
Try to handle date objects only. Convert to strings only when you must: (a) presenting to a human reader, or (b) serializing for storage or transmission.
Working without formatting...
const daysRemainingThisMonth = moment().endOf('month').diff(moment(), 'days');
console.log(`There are ${daysRemainingThisMonth} days remaining this month`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Just as a POJS equivalent, if you have a function to return the last day of the month, you can use that and just get the difference between the two dates, e.g.
function getMonthEnd(date = new Date()) {
return new Date(date.getFullYear(), date.getMonth() + 1, 0);
}
function getMonthDaysLeft(date = new Date()) {
return getMonthEnd(date).getDate() - date.getDate();
}
let d = new Date();
console.log(`There are ${getMonthDaysLeft(d)} days left in ${d.toLocaleString('en',{month:'long'})}.`);
To get a list/array of the days remaining, just loop over a date, adding 1 day at a time, and write the dates in the required format into the list:
function getMonthDaysLeftAsList(date = new Date()) {
let d = new Date(+date);
// Formatter
let f = new Intl.DateTimeFormat('en',{
day: 'numeric',
month: 'short'
});
let m = d.getMonth();
let dayList = [];
while (d.getMonth() == m) {
dayList.push(f.format(d));
d.setDate(d.getDate() + 1);
}
return dayList;
}
console.log(getMonthDaysLeftAsList());

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

MomentJS check if next day and get days apart

How can I check if it's the next day?
const startDate = moment(item.start_time);
const endDate = moment(item.end_time);
const dateDiff = startDate.diff(endDate, 'days', true)
const nextDay = dateDiff > 1
It works for dates like Aug 14th 2PM to Aug 14th 4PM however it doesn't work for dates like Aug 14th 4PM to Aug 14th 2PM.
How can I fix it?
If possible I would like to get the number of days apart they are.
const startDate = moment(item.start_time);
const endDate = moment(item.end_time);
const dateDiff = startDate.diff(endDate, 'days', true) mod 1
Use getDate & setDate methods to increase the current date object by exactly a day. Afterwards you need just compare the date year, month and date.
var isNextDay = function(next, current) {
var date = new Date(current);
date.setDate(date.getDate() + 1);
return (date.getFullYear() === next.getFullYear()) && (date.getMonth() === next.getMonth()) && (date.getDate() === next.getDate());
};
var currentDay = new Date('2016-05-31 16:00:00');
var nextDay = new Date('2016-06-01 14:00:00');
console.log('It is ' + (isNextDay(nextDay, currentDay) ? '' : 'not ') + 'the next day');
Check this code:
var currentDay =new moment('2016-05-31 16:00:00');
var nextDay = new moment('2016-06-01 14:00:00');
console.log('It is ' + (nextDay.isSame(currentDay.add(1, 'days'), 'd') === true ? '' : 'not ') + 'the next day');
jsfiddle

If month is not current month

We have a .NET web service which returns JSON, including a date in string format as follows: 2012-04-30T00:00:00+12:00.
In javascript, I want to exclude dates where the month is not the current month. Hence, with the above date, the month is 04 (April) and the current month is May (in New Zealand anyway). So, I want to ignore this record, e.g, in pseudocode:
if(vMonth == CurrentMonth){
dothis();
}
How can I do this?
EDIT: See Rob G's answer below for the solution that works in all browsers.
var dateOne = new Date("2012-04-30T00:00:00+12:00");​​​
var dateTwo = new Date();
if(dateOne.getMonth() == dateTwo.getMonth()) {
alert("equal");
}
Here's the jsfiddle:
http://jsfiddle.net/Mq5Tf/
More info on the date object:
MSDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
ES5: http://es5.github.com/#x15.9.2
var date = new Date();
var currentMonth = date.getMonth();
var yourMonth = 4;
if(yourMonth == currentMonth ){
/* Do this */
alert('Hello');
}
An alternative that doesn't depend on parsing the date string:
function checkMonth(ds) {
var now = new Date();
var m = now.getMonth() + 1;
return !!ds.match(now.getFullYear() + '-' + (m<10?'0':'') + m);
}
// on 2012-05-01
alert( checkMonth('2012-04-30T00:00:00+12:00') ); // false
alert( checkMonth('2012-05-01T00:00:00+12:00') ); // false
Edit
Note that checking the month number only works where the timezone offset should be ignored or is not significant. While 2012-04-30T00:00:00+12:00 is in April, 2012-04-30T14:00:00+12:00 will be 2am on 1 May local time.
// Means April 30, months are indexes in JS
var input = new Date(2012, 03, 30);​​​
// or use format new date("2012-04-30T00:00:00+12:00") suggested in other answer
var currentDate = new Date();
if(input.getFullYear() == currentDate.getFullYear() // if you care about year
&& input.getMonth() == currentDate.getMonth()) {
// act accordingly
}

How to get year/month/day from a date object?

alert(dateObj) gives Wed Dec 30 2009 00:00:00 GMT+0800
How to get date in format 2009/12/30?
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = year + "/" + month + "/" + day;
or you can set new date and give the above values
new Date().toISOString()
"2016-02-18T23:59:48.039Z"
new Date().toISOString().split('T')[0];
"2016-02-18"
new Date().toISOString().replace('-', '/').split('T')[0].replace('-', '/');
"2016/02/18"
new Date().toLocaleString().split(',')[0]
"2/18/2016"
var dt = new Date();
dt.getFullYear() + "/" + (dt.getMonth() + 1) + "/" + dt.getDate();
Since month index are 0 based you have to increment it by 1.
Edit
For a complete list of date object functions see
Date
getMonth()
Returns the month (0-11) in the specified date according to local time.
getUTCMonth()
Returns the month (0-11) in the specified date according to universal time.
Why not using the method toISOString() with slice or simply toLocaleDateString()?
Beware that the timezone returned by toISOString is always zero UTC offset, whereas in toLocaleDateString it is the user agent's timezone.
Check here:
const d = new Date() // today, now
// Timezone zero UTC offset
console.log(d.toISOString().slice(0, 10)) // YYYY-MM-DD
// Timezone of User Agent
console.log(d.toLocaleDateString('en-CA')) // YYYY-MM-DD
console.log(d.toLocaleDateString('en-US')) // M/D/YYYY
console.log(d.toLocaleDateString('de-DE')) // D.M.YYYY
console.log(d.toLocaleDateString('pt-PT')) // DD/MM/YYYY
I would suggest you to use Moment.js http://momentjs.com/
Then you can do:
moment(new Date()).format("YYYY/MM/DD");
Note: you don't actualy need to add new Date() if you want the current TimeDate, I only added it as a reference that you can pass a date object to it. for the current TimeDate this also works:
moment().format("YYYY/MM/DD");
2021 ANSWER
You can use the native .toLocaleDateString() function which supports several useful params like locale (to select a format like MM/DD/YYYY or YYYY/MM/DD), timezone (to convert the date) and formats details options (eg: 1 vs 01 vs January).
Examples
new Date().toLocaleDateString() // 8/19/2020
new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 08/19/2020 (month and day with two digits)
new Date().toLocaleDateString('en-ZA'); // 2020/08/19 (year/month/day) notice the different locale
new Date().toLocaleDateString('en-CA'); // 2020-08-19 (year-month-day) notice the different locale
new Date().toLocaleString("en-US", {timeZone: "America/New_York"}); // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)
new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}); // 09 (just the hour)
Notice that sometimes to output a date in your specific desire format, you have to find a compatible locale with that format.
You can find the locale examples here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all
Please notice that locale just change the format, if you want to transform a specific date to a specific country or city time equivalent then you need to use the timezone param.
var date = new Date().toLocaleDateString()
"12/30/2009"
info
If a 2 digit month and date is desired (2016/01/01 vs 2016/1/1)
code
var dateObj = new Date();
var month = ('0' + (dateObj.getMonth() + 1)).slice(-2);
var date = ('0' + dateObj.getDate()).slice(-2);
var year = dateObj.getFullYear();
var shortDate = year + '/' + month + '/' + date;
alert(shortDate);
output
2016/10/06
fiddle
https://jsfiddle.net/Hastig/1xuu7z7h/
credit
More info from and credit to this answer
more
To learn more about .slice the try it yourself editor at w3schools helped me understand better how to use it.
let dateObj = new Date();
let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());
For reference you can see the below details
new Date().getDate() // Return the day as a number (1-31)
new Date().getDay() // Return the weekday as a number (0-6)
new Date().getFullYear() // Return the four digit year (yyyy)
new Date().getHours() // Return the hour (0-23)
new Date().getMilliseconds() // Return the milliseconds (0-999)
new Date().getMinutes() // Return the minutes (0-59)
new Date().getMonth() // Return the month (0-11)
new Date().getSeconds() // Return the seconds (0-59)
new Date().getTime() // Return the time (milliseconds since January 1, 1970)
let dateObj = new Date();
let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());
console.log(myDate)
Use the Date get methods.
http://www.tizag.com/javascriptT/javascriptdate.php
http://www.htmlgoodies.com/beyond/javascript/article.php/3470841
var dateobj= new Date() ;
var month = dateobj.getMonth() + 1;
var day = dateobj.getDate() ;
var year = dateobj.getFullYear();
Nice formatting add-in: http://blog.stevenlevithan.com/archives/date-time-format.
With that you could write:
var now = new Date();
now.format("yyyy/mm/dd");
EUROPE (ENGLISH/SPANISH) FORMAT
I you need to get the current day too, you can use this one.
function getFormattedDate(today)
{
var week = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var day = week[today.getDay()];
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
var hour = today.getHours();
var minu = today.getMinutes();
if(dd<10) { dd='0'+dd }
if(mm<10) { mm='0'+mm }
if(minu<10){ minu='0'+minu }
return day+' - '+dd+'/'+mm+'/'+yyyy+' '+hour+':'+minu;
}
var date = new Date();
var text = getFormattedDate(date);
*For Spanish format, just translate the WEEK variable.
var week = new Array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado');
Output: Monday - 16/11/2015 14:24
With the accepted answer, January 1st would be displayed like this: 2017/1/1.
If you prefer 2017/01/01, you can use:
var dt = new Date();
var date = dt.getFullYear() + '/' + (((dt.getMonth() + 1) < 10) ? '0' : '') + (dt.getMonth() + 1) + '/' + ((dt.getDate() < 10) ? '0' : '') + dt.getDate();
Here is a cleaner way getting Year/Month/Day with template literals:
var date = new Date();
var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;
console.log(formattedDate);
It's Dynamic It will collect the language from user's browser setting
Use minutes and hour property in the option object to work with them..
You can use long value to represent month like Augest 23 etc...
function getDate(){
const now = new Date()
const option = {
day: 'numeric',
month: 'numeric',
year: 'numeric'
}
const local = navigator.language
labelDate.textContent = `${new
Intl.DateTimeFormat(local,option).format(now)}`
}
getDate()
You can simply use This one line code to get date in year-month-date format
var date = new Date().getFullYear() + "-" + new Date().getMonth() + 1 + "-" + new Date().getDate();
ES2018 introduced regex capture groups which you can use to catch day, month and year:
const REGEX = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;
const results = REGEX.exec('2018-07-12');
console.log(results.groups.year);
console.log(results.groups.month);
console.log(results.groups.day);
Advantage of this approach is possiblity to catch day, month, year for non-standard string date formats.
Ref. https://www.freecodecamp.org/news/es9-javascripts-state-of-art-in-2018-9a350643f29c/
One liner, using destructuring.
Makes 3 variables of type string:
const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-')
Makes 3 variables of type number (integer):
const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-').map(x => parseInt(x, 10))
From then, it's easy to combine them any way you like:
const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-');
const dateFormatted = `${year}/${month}/${day}`;
I am using this which works if you pass it a date obj or js timestamp:
getHumanReadableDate: function(date) {
if (date instanceof Date) {
return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
} else if (isFinite(date)) {//timestamp
var d = new Date();
d.setTime(date);
return this.getHumanReadableDate(d);
}
}

Categories