How to Match Start Date and End Date [duplicate] - mongodb

How to get start ( 00:00:00 ) and end ( 23:59:59 ) of today in timestamp ( GMT )? Computer use a local time.

var start = new Date();
start.setUTCHours(0,0,0,0);
var end = new Date();
end.setUTCHours(23,59,59,999);
alert( start.toUTCString() + ':' + end.toUTCString() );
If you need to get the UTC time from those, you can use UTC().

With dayjs library, use startOf and endOf methods as follows:
Local GMT:
const start = dayjs().startOf('day'); // set to 12:00 am today
const end = dayjs().endOf('day'); // set to 23:59 pm today
For UTC:
const utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
const start = dayjs.utc().startOf('day');
const end = dayjs.utc().endOf('day');
Using the (deprecated) momentjs library, this can be achieved with the startOf() and endOf() methods on the moment's current date object, passing the string 'day' as arguments:
Local GMT:
var start = moment().startOf('day'); // set to 12:00 am today
var end = moment().endOf('day'); // set to 23:59 pm today
For UTC:
var start = moment.utc().startOf('day');
var end = moment.utc().endOf('day');

Using the luxon.js library, same can be achieved using startOf and endOf methods by passing the 'day' as parameter
var DateTime = luxon.DateTime;
DateTime.local().startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z
DateTime.local().endOf('day').toUTC().toISO(); //2017-11-17T18:29:59.999Z
DateTime.fromISO(new Date().toISOString()).startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z
remove .toUTC() if you need only the local time
and you may ask why not moment.js, answer is here for that.

FYI (merged version of Tvanfosson)
it will return actual date => date when you are calling function
export const today = {
iso: {
start: () => new Date(new Date().setHours(0, 0, 0, 0)).toISOString(),
now: () => new Date().toISOString(),
end: () => new Date(new Date().setHours(23, 59, 59, 999)).toISOString()
},
local: {
start: () => new Date(new Date(new Date().setHours(0, 0, 0, 0)).toString().split('GMT')[0] + ' UTC').toISOString(),
now: () => new Date(new Date().toString().split('GMT')[0] + ' UTC').toISOString(),
end: () => new Date(new Date(new Date().setHours(23, 59, 59, 999)).toString().split('GMT')[0] + ' UTC').toISOString()
}
}
// how to use
today.local.now(); //"2018-09-07T01:48:48.000Z" BAKU +04:00
today.iso.now(); // "2018-09-06T21:49:00.304Z" *
* it is applicable for Instant time type on Java8 which convert your local time automatically depending on your region.(if you are planning write global app)

In MomentJs We can declare it like :
const start = moment().format('YYYY-MM-DD 00:00:01');
const end = moment().format('YYYY-MM-DD 23:59:59');

One liner - considering local timezone and without libraries
const todayStart = new Date(new Date().setHours(0, 0, 0, 0))
const todayEnd = new Date(new Date().setHours(23, 59, 59, 999))
const tomorrowStart = new Date(new Date(new Date().setHours(0, 0, 0, 0)).setDate(new Date().getDate() + 1))
const tomorrowEnd = new Date(new Date(new Date().setHours(23, 59, 59, 999)).setDate(new Date().getDate() + 1))
const monthStart = new Date(new Date(new Date().getFullYear(), new Date().getMonth(), 1).setHours(0, 0, 0, 0))
const monthEnd = new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).setHours(23, 59, 59, 999))
const nextMonthStart = new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1).setHours(0, 0, 0, 0))
const nextMonthEnd = new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 2, 0).setHours(23, 59, 59, 999))
console.log({
todayStart,
todayEnd,
tomorrowStart,
tomorrowEnd,
monthStart,
monthEnd,
nextMonthStart,
nextMonthEnd,
})

If you're just interested in timestamps in GMT you can also do this, which can be conveniently adapted for different intervals (hour: 1000 * 60 * 60, 12 hours: 1000 * 60 * 60 * 12, etc.)
const interval = 1000 * 60 * 60 * 24; // 24 hours in milliseconds
let startOfDay = Math.floor(Date.now() / interval) * interval;
let endOfDay = startOfDay + interval - 1; // 23:59:59:9999

I prefer to use date-fns library for date manipulating. It is really great modular and consistent tool. You can get start and end of the day this way:
var startOfDay = dateFns.startOfDay;
var endOfDay = dateFns.endOfDay;
console.log('start of day ==> ', startOfDay(new Date('2015-11-11')));
console.log('end of day ==> ', endOfDay(new Date('2015-11-11')));
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>

We can use moment for this.
// for day start time
moment(moment().startOf('day')).format('HH:mm')
// for day end time
moment(moment().endOf('day')).format('HH:mm')

As you are interested in the UTC start/end of day, you can also use the modulo operator:
const now = new Date().getTime();
let startOfDay = now - (now % 86400000);
let endDate = startOfDay + 86400000;
where 86400 is the number of seconds of one day and the resulting variables are the Epoch in milliseconds.
If you prefer Date Objects:
const now = new Date().getTime();
let startOfDay = new Date(now - (now % 86400000));
let endDate = new Date(now - (now % 86400000) + 86400000);

Based on the most rated answer, but to define the dates in just one line:
const startToday = new Date(new Date().setUTCHours(0,0,0,0));
const endToday = new Date(new Date().setUTCHours(23,59,59,999));
Explanation:
new Date().setUTCHours(0,0,0,0) // returns the epoch time number
new Date(/* epoch number */) // returns that epoch Date object
that is why both new Date constructors are needed.

It might be a little tricky, but you can make use of Intl.DateTimeFormat.
The snippet bellow can help you convert any date with any timezone to its begining/end time.
const beginingOfDay = (options = {}) => {
const { date = new Date(), timeZone } = options;
const parts = Intl.DateTimeFormat("en-US", {
timeZone,
hourCycle: "h23",
hour: "numeric",
minute: "numeric",
second: "numeric",
}).formatToParts(date);
const hour = parseInt(parts.find((i) => i.type === "hour").value);
const minute = parseInt(parts.find((i) => i.type === "minute").value);
const second = parseInt(parts.find((i) => i.type === "second").value);
return new Date(
1000 *
Math.floor(
(date - hour * 3600000 - minute * 60000 - second * 1000) / 1000
)
);
};
const endOfDay = (...args) =>
new Date(beginingOfDay(...args).getTime() + 86399999);
const beginingOfYear = () => {};
console.log(beginingOfDay({ timeZone: "GMT" }));
console.log(endOfDay({ timeZone: "GMT" }));
console.log(beginingOfDay({ timeZone: "Asia/Tokyo" }));
console.log(endOfDay({ timeZone: "Asia/Tokyo" }));

// get current time for UTC timezone
const d = new Date();
const year = d.getUTCFullYear();
const month = d.getUTCMonth();
const day = d.getUTCDate();
// set time to begin day UTC
const startTime = Date.UTC(year, month, day, 0, 0, 0, 0);
//set time to end day UTC
const endTime = Date.UTC(year, month, day, 23, 59, 0, 0);

Related

How I to find and add any input field in the synch fusion calendar code?

var generateEvents = function () {
var eventData = [];
var eventSubjects = [
'Bering Sea Gold', 'Technology', 'Maintenance', 'Meeting', 'Travelling', 'Annual Conference', 'Birthday Celebration',
'Farewell Celebration', 'Wedding Anniversary', 'Alaska: The Last Frontier', 'Deadliest Catch', 'Sports Day', 'MoonShiners',
'Close Encounters', 'HighWay Thru Hell', 'Daily Planet', 'Cash Cab', 'Basketball Practice', 'Rugby Match', 'Guitar Class',
'Music Lessons', 'Doctor checkup', 'Brazil - Mexico', 'Opening ceremony', 'Final presentation'
];
var weekDate = new Date(new Date().setDate(new Date().getDate() - new Date().getDay()));
var startDate = new Date(weekDate.getFullYear(), weekDate.getMonth(), weekDate.getDate(), 10, 0);
var endDate = new Date(weekDate.getFullYear(), weekDate.getMonth(), weekDate.getDate(), 11, 30);
eventData.push({
Id: 1,
Subject: eventSubjects[Math.floor(Math.random() * (24 - 0 + 1) + 0)],
StartTime: startDate,
EndTime: endDate,
Location: '',
Description: 'Event Scheduled',
RecurrenceRule: 'FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR;INTERVAL=1;COUNT=10;',
IsAllDay: false,
IsReadonly: false,
CalendarId: 1
});
I have tried inspecting the code and tried to add the input field eventData, but not working. I want to add the Input field of my choice and want to send the input field data to the firestore database.

Enable Particular Date in datepicker

I have disabled all Mondays in datepicker but on some dates I have to enable that particular date on Monday, so how can I do that? I have pasted the code :
const datepicker2 = new Datepicker(elem2, {
daysOfWeekDisabled: dates_diable,
beforeShowDay: function(date) {
dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
console.log(dmy+' : '+($.inArray(dmy, availableDates)));
if ($.inArray(dmy, availableDates) > '-1') {
//console.log('yes');
return true;
}
},
format: 'dd/mm/yyyy',
buttonClass: 'btn',
minDate:"Today",
maxDate:maxDate,
datesDisabled: [],
todayHighlight: false,
});

Display the name of the month in the date

I display a date range in my code, which appears as this: 06-08-2017 - 12-08-2017.
But what I would like to see is this: 06 August - 12 August
I wondered how to do it.
Here is the code I use to display dates:
<script>
$(document).ready(function() {
var startDate;
var endDate;
// configure the bootstrap datepicker
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('#js-datepicker').find('.ui-datepicker-current-day a').addClass('ui-state-active')
}, 1);
}
$('#js-datepicker').datepicker({
//config default
altField: "#datepicker",
closeText: 'Fermer',
prevText: 'Précédent',
nextText: 'Suivant',
currentText: 'Aujourd\'hui',
monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
monthNamesShort: ['Janv.', 'Févr.', 'Mars', 'Avril', 'Mai', 'Juin', 'Juil.', 'Août', 'Sept.', 'Oct.', 'Nov.', 'Déc.'],
dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
dayNamesShort: ['Dim.', 'Lun.', 'Mar.', 'Mer.', 'Jeu.', 'Ven.', 'Sam.'],
dayNamesMin: ['D', 'L', 'M', 'M', 'J', 'V', 'S'],
weekHeader: 'Sem.',
dateFormat: 'dd-mm-yy',
firstDay: 1,
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function(date,obj){
var daty = $(this).datepicker('getDate');
console.log(daty);
startDate = new Date(daty.getFullYear(), daty.getMonth(), daty.getDate() - daty.getDay());
endDate = new Date(daty.getFullYear(), daty.getMonth(), daty.getDate() - daty.getDay() + 6);
var dateFormat = obj.settings.dateFormat || $.datepicker._defaults.dateFormat;
$('#startDate').text($.datepicker.formatDate( dateFormat, startDate, obj.settings ));
$('#endDate').text($.datepicker.formatDate( dateFormat, endDate, obj.settings ));
selectCurrentWeek();
date = $.datepicker.formatDate('dd-mm-yy', daty);
console.log(date);
$('#date_input').val(date);
}
});
});
</script>
Thank you
Try this :
dateFormat: 'dd-MMMM',
A good library for date format is
http://momentjs.com
From the documentation
moment().format('MMMM Do YYYY, h:mm:ss a'); // August 13th 2017, 8:26:44

Datetime formatting / customization in ejs

I show date by this in ejs
<%= new Date();%>
it give me result
Tue Feb 02 2016 16:02:24 GMT+0530 (IST)
But I need to show as
19th January, 2016
How can I do this in ejs?
You can use moment
In your controller,
var moment = require('moment');
exports.index = function(req, res) {
res.render('index', { moment: moment });
}
In your html,
<html>
<h1><%= moment().format('Do MMMM, YYYY'); %></h1>
</html>
EDIT :
Using basic JS
const suffixMap = {
one: 'st',
two: 'nd',
few: 'rd',
other: 'th',
};
const date = new Date();
const dateDay = date.getDate();
const dateMonth = date.toLocaleString('default', {month: 'long'});
const dateYear = date.getFullYear();
const pluralRule = new Intl.PluralRules('en-GB', {type: 'ordinal'});
const dateOrdinal = suffixMap[pluralRule.select(dateDay)]
const ordinalDateString = `${dateDay}${dateOrdinal} ${dateMonth}, ${dateYear}`;
// Expected output: 25th August, 2020
(Adapted from this answer)
const date = new Date();
const dateDay = date.getDate();
const dateMonth = date.toLocaleString('default', {month: 'long'});
const dateYear = date.getFullYear();
// DETERMINE DATE ORDINAL
let dateOrdinal = 'th';
dateOrdinal = ([1, 21, 31].indexOf(dateDay) > -1) ? 'st' : dateOrdinal;
dateOrdinal = ([2, 22].indexOf(dateDay) > -1) ? 'nd' : dateOrdinal;
dateOrdinal = ([3, 23].indexOf(dateDay) > -1) ? 'rd' : dateOrdinal;
// FORMAT DATE AS STRING
const ordinalDateString = `${dateDay}${dateOrdinal} ${dateMonth}, ${dateYear}`;
// Expected output: 25th August, 2020
Or, if you can live without ordinal day (th, nd, rd etc) you could use basic JS
<%= new Intl.DateTimeFormat('en-GB', { year: 'numeric', month: 'long', day: '2-digit'}).format(new Date()) %>
// Expected output: 25 August 2020
You don't need moment js, you can simply use this
<%= new Date().getFullYear();%>
Post is old but in case anyone runs into the issue.
You can eliminate installing moment and write one little line of code.
adding .toDateString() will provide you with the above format in ejs.
however, Moment is used for more detailed date, such as Day, or month or year etc...
For a better code management, you can add the code(below) in app.js/server.js. This will save moment in the res.locals.moment at the time of starting the app. By doing this you can access the moment variable from any ejs page.
app.js/server.js:
const express = require("express");
const app = express();
const moment = require("moment");
app.use((req, res, next)=>{
res.locals.moment = moment;
next();
});
something.ejs
<p><%= moment(yourDateVariable).format('Do MMMM, YYYY') %></p>
Here Do will result with 19th.You can check it here https://momentjs.com/docs/#/displaying/format/. Hope this will help.
You can do this:
<%= moment(user.date).format( 'MMM-DD-YYYY') %>
The problem with most of the answers on this page is that they will format the date using the server's locale, but you probably want them rendered in the user's locale. For example, if your server is in Virginia, your dates will be displayed in English in Eastern Time, but a user in another country will probably want them displayed differently.
The following code snippet will render date using the user's locale. There's room for improvement, but it's a starting point:
<p>
<script type="text/javascript">
document.write(
new Date("<%= date.toISOString() %>").toLocaleDateString()
);
</script>
</p>
This takes the date on the server, converts it to an ISO-8601 string, and interpolates it into a little JavaScript snippet that runs client-side to produce the correct localized output.
For more information on toLocaleString, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
// I have tested this in a for loop, it seems to be ok.
<% let d = new Date(); %>
<% let day = d.getDate(); %>
<% let m = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"]; %>
<% let month = m[d.getMonth()]; %>
<% let year = d.getFullYear(); %>
<% let newdate = day + "th " + month + ", " + year; %>
<%= newdate %> // 22th July, 2022
// You can use the if...else statement for the ordinal number

Count days between two dates excluding weekends

How can I find the difference between two dates in DB2 (excluding weekends)?
Are there any functions that will do this in DB2? Or do I need to write a query myself?
There is AFAIK no such function. It is however easy to write a query that calculates this:
with cal(d) as (
values date('2015-01-01') -- start_date
union all
select d + 1 day from cal
where d < '2015-01-15' -- end_date
) select count(case when dayofweek(d) between 2 and 6 then 1 end)
from cal;
If you do a lot of these kind of calculations you might want to create a calendar table, you can add attributes like national holiday etc to this table.
you can use this function:
DAYOFWEEK(CURRENT_DATE)
The following calculation will return the number of working days between two dates:
[Week(End Date) - Week(Start Date)] * 5 + [DayofWeek(Start Date) - DayofWeek(End Date)]
This will only work if the functions for Week and Day or equivalent are native to the database driver. Client Access and Sybase native connection both support these functions.
The Week function will give the integer value of the week of the year selected. The DayofWeek will give an Integer value from 1-7 for the day selected.
IBM Support Working Days Between Two Dates
This is the best way to implement difference between two dates excluding weekend means Saturday and Sunday and also excluding national holiday....
/******
* First, we'll extend the date object with some functionality.
* We'll add an .each() function, as well as an .adjust() function.
* .each() will give us the ability to loop between two dates, whether
* by 'day', 'week' or 'month'.
* .adjust() will allow us to move a given day by a given unit. This is used
* like so: currentDate.adjust('days', 1) to increment by one day.
******/
Date.prototype.each = function(endDate, part, step, fn, bind){
var fromDate = new Date(this.getTime()),
toDate = new Date(endDate.getTime()),
pm = fromDate <= toDate? 1:-1,
i = 0;
while( (pm === 1 && fromDate <= toDate) || (pm === -1 && fromDate >= toDate) ){
if(fn.call(bind, fromDate, i, this) === false) break;
i += step;
fromDate.adjust(part, step*pm);
}
return this;
};
Date.prototype.adjust = function(part, amount){
part = part.toLowerCase();
var map = {
years: 'FullYear', months: 'Month', weeks: 'Hours', days: 'Hours', hours: 'Hours',
minutes: 'Minutes', seconds: 'Seconds', milliseconds: 'Milliseconds',
utcyears: 'UTCFullYear', utcmonths: 'UTCMonth', weeks: 'UTCHours', utcdays: 'UTCHours',
utchours: 'UTCHours', utcminutes: 'UTCMinutes', utcseconds: 'UTCSeconds', utcmilliseconds: 'UTCMilliseconds'
},
mapPart = map[part];
if(part == 'weeks' || part == 'utcweeks')
amount *= 168;
if(part == 'days' || part == 'utcdays')
amount *= 24;
this['set'+ mapPart]( this['get'+ mapPart]() + amount );
return this;
}
/*******
* An array of national holidays. This is used to test for the exclusion of given
* days. While this list is national days, you could tailor it to regional, state
* or given religious observances. Whatever.
******/
natDays = [
{
month: 1,
date: 26,
type: "national - us",
name: "New Year's Day"
},
{
month: 1,
date: 21,
type: "national - us",
name: "Martin Luther King Day"
},
{
month: 2,
date: 18,
type: "national - us",
name: "President's Day (Washington's Birthday"
},
{
month: 5,
date: 27,
type: "national - us",
name: "Memorial Day"
},
{
month: 7,
date: 4,
type: "national - us",
name: "Independence Day"
},
{
month: 9,
date: 2,
type: "national - us",
name: "Labor Day"
},
{
month: 10,
date: 14,
type: "national - us",
name: "Columbus Day"
},
{
month: 11,
date: 11,
type: "national - us",
name: "Veteran's Day"
},
{
month: 11,
date: 29,
type: "national - us",
name: "Thanksgiving Day"
},
{
month: 12,
date: 25,
type: "national - us",
name: "Christmas Day"
}
];
/******
* This uses the national holidays array we just set, and checks a given day to see
* if it's in the list. If so, it returns true and the name of the holiday, if not
* it returns false.
*****/
function nationalDay(date) {
for (i = 0; i < natDays.length; i++) {
if (date.getMonth() == (natDays[i].month-1)
&& date.getDate() == natDays[i].date) {
return [true, natDays[i].name];
}
}
return [false, null];
}
/******
* This function takes two dates, as start and end date, and iterates through the
* dates between them. For each date, it checks if the current date is a week day.
* If it is, it then checks if it isn't a holiday. In this case, it increments
* the business day counter.
******/
function calcBusinessDays(startDate, endDate) {
// input given as Date objects
var iDateDiff=0, holidays = [];
startDate.each(endDate, 'days', 1, function(currentDate, currentStep, thisDate){
if(currentDate.getDay() != 0 && currentDate.getDay() != 6 ) {
var isAHoliday = nationalDay(currentDate);
if(!isAHoliday[0]){
iDateDiff += 1;
} else {
holidays.push(isAHoliday[1]);
}
}
});
return {count: iDateDiff, holidays: holidays};
};
$(function(){
var results, exclusions;
$( "#startDate" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#endDate" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#endDate" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#startDate" ).datepicker( "option", "maxDate", selectedDate );
}
});
$("#calculateMe").on("click", function(){
var startDate = new Date($("#startDate").val()),
endDate = new Date($("#endDate").val() );
// Calculate the number of business days. This returns an object, with
// two members: count and holidays
results = calcBusinessDays(startDate, endDate);
exclusions = "Excluded weekends";
if (results.holidays.length > 0) {
// We have holidays, tell the user about them...
exclusions += " and the following holidays: ";
for(var i=0; i<results.holidays.length; i += 1){
exclusions += results.holidays[i]+", ";
}
} else {
// No holidays.
exclusions += ".";
}
$("#result").text(results.count + " business days." ).append("<p>("+exclusions+")</p>");
});
});
<div id="content">
<input type="text" class="myDateClass" id="startDate"/>
<input type="text" class="myDateClass" id="endDate"/>
<button id="calculateMe">How many business days?</button>
<div id="result"></div>
</div>
Fiddle