generate date range base on integers - javascript

I have an array like this [0,1,2,3 .. 23] and they means hour in a day. How to use moment js to convert them to 12 hour then do date range?
my desire output is
['12am-1am','1am-2am','2am-3am' .. 11pm-12am]
my attempt failed coz I thought I don't need moment https://jsfiddle.net/s4L7hj1a

You don't need moment.js
var getFormattedHour = function(hour) {
return (hour % 12 ? hour % 12 : 12) + ':00 ' + ((hour < 12) || (hour >= 24) ? 'AM' : 'PM');
}
var getHourRange = function(hour) {
return getFormattedHour(hour) + ' - ' + getFormattedHour(hour + 1);
}
var hours = [];
for(var hour = 0; hour < 24; hour++) {
hours.push(hour);
}
hours.map(function(hour) {
console.log(getHourRange(hour));
});

Using moment.js:
const moment = require('moment');
const start = moment().startOf('day');
const times = 24; // 24 hours
for (let i = 0; i < times; i++) {
const toPrint = moment(start)
.add(60 * i, 'minutes')
.format('hh:mm A');
console.log(toPrint);
}
This will give yo:
12:00 AM
01:00 AM
02:00 AM
...
...
10:00 PM
11:00 PM
then you can add them in array as you like

Related

How to compare two times in javascript

I'm struggling to compare two times.
I need to print Current class going based on the current time.
Example: current time based class going on the college/school
var now = new Date();
var TwentyFourHour = now.getHours();
var hour = now.getHours();
var min = now.getMinutes();
var mid = 'PM';
if (min < 10) {
min = "0" + min;
}
if (hour > 12) {
hour = hour - 12;
}
if (hour == 0) {
hour = 12;
}
if (TwentyFourHour < 12) {
mid = 'AM';
}
Current_time = hour + ':' + min + ':' + mid;
start_time = "09:00:PM";
end_time = "10:00:PM";
if (parseInt(start_time) <= parseInt(Current_time) || parseInt(end_time) >= parseInt(Current_time)) {
console.log("C programming class is going");
} else {
console.log("No class are avalible");
}
OUTPUT:
C programming class is going....
It seems you are looking for the shortest path to have your homework done.
Please check the references for Date function:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
Some tips:
Make sure you understand how the Date object is created. You can use strings!
If you want to define date manually using each day, month , value, you can!
Check your strings.. are you sure "09:00:PM" is a valid string for date?
Are you sure you can use parseInt for parsing dates?
Anyway, you need to do more research.
The easiest way to check if a time is between a start and an end time is to store the time using unix time(https://en.wikipedia.org/wiki/Unix_time). It represents the time in seconds after 00:00:00 UTC on 1 January 1970. so you can do the following:
const startTime = 1624802400 // 27.6.21 16:00
const endTime = 1624809600 //27.6.21 18:00
const currentTime = Date.now()/1000
if(currentTime < endTime && currentTime > startTime){
console.log('Class is going')
}
if(currentTime > endTime){
console.log('Class ended')
}
if(currentTime < startTime){
console.log('Class has not started')
}
Date.now() returns the current time in milliseconds so you need to divide it by 1000

Time difference between 2 datetime moment

SO i have 2 datetime objects .
now = Nov 15 4:00 PM
later = Nov 15 6:00PM
My objective is to get the total hours between (9AM to 5 PM) , given the now and later times.
resulting answer shud be 1 hour. (since im only concerned about time range that falls within 9AM-5PM)
now = Nov 15 6:00 AM
later = Nov 15 8:00 PM
resulting answer should be 8 hours.
is the best way to achieve this using the diff function in moment and stripping the hour out and calculating individual use cases ( when start time less than 9AM/ start time greater than 9AM) . similarly end time (less than 5PM/greater than 5PM) etc?
Also how to tackle this case where,
now = Nov 15 9:00AM
later = Nov 18 2:00PM
resulting answer shud be ,
8(nov 15)+8(nov 16)+8(nov 17)+5(nov 18) = 29hrs
Here's working solution
var now = moment("15 Nov 2016, 9:00:00 am", "DD MMM yyyy, h:mm:ss a").toDate();
var later = moment("18 Nov 2016, 2:00:00 pm", "DD MMM yyyy, h:mm:ss a").toDate();
function getWorkingHours(now, later) {
var hoursToday = 0;
var workingHourStart = 9;
var workingHourEnd = 17;//5pm
var workDuration = workingHourEnd - workingHourStart;
if(workingHourEnd - getHours(now) > 0) {
hoursToday = (workingHourEnd - getHours(now));
hoursToday = (hoursToday > workDuration) ? workDuration : hoursToday;
}
var hoursLater = 0;
if(getHours(later) - workingHourStart > 0) {
hoursLater = (getHours(later) - workingHourStart);
hoursLater = (hoursLater > workDuration) ? workDuration : hoursLater;
}
var actualDiffHours = (later.getTime() - now.getTime()) / (1000 * 60 * 60);
var actualHoursInBetween = actualDiffHours - (24 - getHours(now)) - getHours(later);
var workingHoursInBetween = (actualHoursInBetween / 24) * 8;
return hoursToday + workingHoursInBetween + hoursLater;
}
function getHours(date) {
var hours = date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600 + date.getMilliseconds() / 3600/1000;
return hours;
}
console.log(getWorkingHours(now, later));
<script src="http://momentjs.com/downloads/moment.min.js"></script>
This should do the job:
const now = moment(new Date(2016, 11, 15, 9, 0, 0));
const then = moment(new Date(2016, 11, 18, 14, 0, 0));
function calDiff(now, then) {
if (now.hour() < 9) {
now.hour(9);
}
if (then.hour() > 17) {
then.hour(17);
}
const total = then.diff(now, 'hours');
const day = Math.floor(total / 24);
return total - (16 * day);
}
console.log(calDiff(now, then));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>
Complicated... Function getActiveHours calculates all active slots between start and finish dates, both inclusive, and then removes the missing hours at the beginning of the start date and at the end of the finish date.
var getDateObject = function (date) {
if (date && date.constructor.name == "Array") {
while (date.length < 7) {date.push(0);}
date = new Date(date[0], date[1], date[2], date[3], date[4], date[5], date[6]);
} else if (typeof date == 'string' || typeof date == 'number') {
date = new Date(date);
}
return date;
};
var trimDate = function (date, period) {
var periods = ['second', 'minute', 'hour', 'day'];
period = periods.indexOf(period);
if (typeof date != 'number') {date = getDateObject(date).getTime();}
date = Math.floor(date/1000);
if (period > 0) {date = Math.floor(date/60);}
if (period > 1) {date = Math.floor(date/60);}
if (period > 2) {date = Math.floor(date/24);}
return new Date(date*24*60*60*1000);
};
var getOffset = function (date) {return getDateObject(date).getTimezoneOffset()*60*1000;};
var addOffset = function (date) {
date = getDateObject(date);
return new Date(date.getTime()+getOffset(date));
};
var getActiveHours = function (iniDateTime, endDateTime, startHour, finishHour) {
var hourMs = 60*60*1000; // Define daily active hours 0-24 (decimal 17.5 = 5:30pm):
if (startHour == null) {startHour = 9;}
if (finishHour == null) {finishHour = 17;}
startHour *= hourMs; finishHour *= hourMs;
iniDateTime = getDateObject(iniDateTime).getTime();
endDateTime = getDateObject(endDateTime).getTime();
var iniDayTime = addOffset(trimDate(iniDateTime, 'day')).getTime();
var endDayTime = addOffset(trimDate(endDateTime, 'day')).getTime();
var totalHoursMs = (endDayTime-iniDayTime+24*hourMs)*(finishHour-startHour)/hourMs/24;
var iniHoursNotInMs = iniDateTime-iniDayTime-startHour;
var endHoursNotInMs = endDayTime+finishHour-endDateTime;
return (totalHoursMs-iniHoursNotInMs-endHoursNotInMs)/hourMs;
};
console.log(Math.round(getActiveHours('2016-09-13 11:45:38', '2016-09-15 15:30:25'))); // 20 // Use Math round or floor
I had started writing this awhile back when I first saw the question, but got caught up. My answer is very similar to Khang's, but we went about a certain section of it a little differently.
The basic idea behind the code is that it takes two moment objects. If the start hours are less than nine, we set them to be nine, and if the end hours are greater than 17 (5pm) we set them to be 17.
Next we get the difference between the two objects in days. For each day we know that there are 8 hours the person can get credit for. I then move the date of the start day to the end day, and take the hours between them.
The idea behind this is that if both times are within the same days, there will be 0 days difference. If it is 1, then we will get a total of 8 hours regardless where we start in the day. the only cases I haven't tested are things where the start time is greater than the end time (I'll test it ASAP and make an edit if there's anything I need to change)
Edit
there was indeed a problem if the start time was after the end time (the hours).
This was fixed by adding in one if statement.
$(function() {
function getActiveHours(start, end) {
if (start.hours() < 9) start.hours(9);
if (end.hours() > 17) end.hours(17);
//These two if's should remove most of the issues when we are doing basic work
var days = end.diff(start, 'days');
if (days == 0 && (end.date() - start.date()) == 1) days = 1;
var hours = (days * 8); //gets the hours
start.date(end.date());
var diff = end.diff(start, 'hours');
return hours + diff;
}
var start = moment([2016, 10, 15, 9, 0, 0]);
var end = moment([2016, 10, 18, 14, 0, 0]);
$('#results').html('Total hours worked from ' + start.format('MM-DD-YYYY # hh:mm:ss') + ' to ' + end.format('MM-DD-YYYY # hh:mm:ss') + ' is ' + getActiveHours(start, end))
});
<div id="results"></div>

How to convert string to Time with javascript [duplicate]

Please see the below code;
var d = new Date();
var s = "01.00 AM";
d.setTime(s);
I know this code is wrong. Please give me the correct way to set the time. I have 12 hour time in string format in my hand.
The time will vary. Cannot know what will be the time earlier. Also it is 12 hour time. So it will be AM or PM
You can parse the time with a regex, and set the hours and minutes accordingly:
http://jsfiddle.net/54VkC/1/
var d = new Date(),
s = "01.25 PM",
parts = s.match(/(\d+)\.(\d+) (\w+)/),
hours = /am/i.test(parts[3]) ? parseInt(parts[1], 10) : parseInt(parts[1], 10) + 12,
minutes = parseInt(parts[2], 10);
d.setHours(hours);
d.setMinutes(minutes);
alert(d);
Edit 1:
As jaisonDavis pointed out, the original code will not work for AM or PM for 12.XX, which was an oversight since I never use 12-hour format myself, thinking it started at 00.00 which was wrong.
The corrected code which handles these cases can be seen here:
http://jsfiddle.net/54VkC/93/
var test, parts, hours, minutes, date,
d = (new Date()).getTime(),
tests = ['01.25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
i = tests.length,
timeReg = /(\d+)\.(\d+) (\w+)/;
for(; i-- > 0;) {
test = tests[i];
parts = test.match(timeReg);
hours = /am/i.test(parts[3]) ?
function(am) {return am < 12 ? am : 0}(parseInt(parts[1], 10)) :
function(pm) {return pm < 12 ? pm + 12 : 12}(parseInt(parts[1], 10));
minutes = parseInt(parts[2], 10);
date = new Date(d);
date.setHours(hours);
date.setMinutes(minutes);
console.log(test + ' => ' + date);
}
I'm late to the party, but I thought I'd share a funtion that doesn't use regex:
function setDateTime(date, time) {
var index = time.indexOf("."); // replace with ":" for differently displayed time.
var index2 = time.indexOf(" ");
var hours = time.substring(0, index);
var minutes = time.substring(index + 1, index2);
var mer = time.substring(index2 + 1, time.length);
if (mer == "PM"){
hours = hours + 12;
}
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds("00");
return date;
}
Using moment.js will be the easy solution.
const fullDate = new Date();
// fullDate = Tue Dec 12 2017 11:18:30 GMT+0530 (IST) {}
const time = '01.00 AM';
const d = moment(fullDate).format('L'); // d = "12/12/2017"
const date = moment(d +' '+ time).format();
// date = "2017-12-12T01:00:00+05:30"
If you want convert moment date to js date
const jsDate = moment(date).toDate();
function getCurrentDate() {
var lDate = new Date();
var lDay = lDate.getDate();
var lMonth = lDate.getMonth() + 1;
var lYear = lDate.getFullYear();
if (lDay < 10) {
lDay = '0' + lDay
}
if (lMonth < 10) {
lMonth = '0' + lMonth
}
mCurrentDate = lYear + "-" + lMonth + "-" + lDay + "T00:00:00+05:30";
}
I added a few things as an improvement to the accepted answer by #thebreiflabb to suit my use case and thought i'd share.
if the regex is changed to timeReg = /(\d+)[\.|:](\d+)\s?(\w+)/;,
it'll handle a few other common cases.
namely:
using a colon instead of decimal point between hours and minutes
allowing am/pm to immediately follow the time with no space
also, setting the seconds to 0 (since that was my main use case)
the resulting code would be:
var test, parts, hours, minutes, date,
d = (new Date()).getTime(),
tests = ['01.25 PM', '01:25pm', '1:25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
i = tests.length,
timeReg = /(\d+)[\.|:](\d+)\s?(\w+)/;
for(; i-- > 0;) {
test = tests[i];
parts = test.match(timeReg);
hours = /am/i.test(parts[3]) ?
function(am) {return am < 12 ? am : 0}(parseInt(parts[1], 10)) :
function(pm) {return pm < 12 ? pm + 12 : 12}(parseInt(parts[1], 10));
minutes = parseInt(parts[2], 10);
date = new Date(d);
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds(0);
console.log(test + ' => ' + date);
}

Javascript set time string to date object

Please see the below code;
var d = new Date();
var s = "01.00 AM";
d.setTime(s);
I know this code is wrong. Please give me the correct way to set the time. I have 12 hour time in string format in my hand.
The time will vary. Cannot know what will be the time earlier. Also it is 12 hour time. So it will be AM or PM
You can parse the time with a regex, and set the hours and minutes accordingly:
http://jsfiddle.net/54VkC/1/
var d = new Date(),
s = "01.25 PM",
parts = s.match(/(\d+)\.(\d+) (\w+)/),
hours = /am/i.test(parts[3]) ? parseInt(parts[1], 10) : parseInt(parts[1], 10) + 12,
minutes = parseInt(parts[2], 10);
d.setHours(hours);
d.setMinutes(minutes);
alert(d);
Edit 1:
As jaisonDavis pointed out, the original code will not work for AM or PM for 12.XX, which was an oversight since I never use 12-hour format myself, thinking it started at 00.00 which was wrong.
The corrected code which handles these cases can be seen here:
http://jsfiddle.net/54VkC/93/
var test, parts, hours, minutes, date,
d = (new Date()).getTime(),
tests = ['01.25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
i = tests.length,
timeReg = /(\d+)\.(\d+) (\w+)/;
for(; i-- > 0;) {
test = tests[i];
parts = test.match(timeReg);
hours = /am/i.test(parts[3]) ?
function(am) {return am < 12 ? am : 0}(parseInt(parts[1], 10)) :
function(pm) {return pm < 12 ? pm + 12 : 12}(parseInt(parts[1], 10));
minutes = parseInt(parts[2], 10);
date = new Date(d);
date.setHours(hours);
date.setMinutes(minutes);
console.log(test + ' => ' + date);
}
I'm late to the party, but I thought I'd share a funtion that doesn't use regex:
function setDateTime(date, time) {
var index = time.indexOf("."); // replace with ":" for differently displayed time.
var index2 = time.indexOf(" ");
var hours = time.substring(0, index);
var minutes = time.substring(index + 1, index2);
var mer = time.substring(index2 + 1, time.length);
if (mer == "PM"){
hours = hours + 12;
}
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds("00");
return date;
}
Using moment.js will be the easy solution.
const fullDate = new Date();
// fullDate = Tue Dec 12 2017 11:18:30 GMT+0530 (IST) {}
const time = '01.00 AM';
const d = moment(fullDate).format('L'); // d = "12/12/2017"
const date = moment(d +' '+ time).format();
// date = "2017-12-12T01:00:00+05:30"
If you want convert moment date to js date
const jsDate = moment(date).toDate();
function getCurrentDate() {
var lDate = new Date();
var lDay = lDate.getDate();
var lMonth = lDate.getMonth() + 1;
var lYear = lDate.getFullYear();
if (lDay < 10) {
lDay = '0' + lDay
}
if (lMonth < 10) {
lMonth = '0' + lMonth
}
mCurrentDate = lYear + "-" + lMonth + "-" + lDay + "T00:00:00+05:30";
}
I added a few things as an improvement to the accepted answer by #thebreiflabb to suit my use case and thought i'd share.
if the regex is changed to timeReg = /(\d+)[\.|:](\d+)\s?(\w+)/;,
it'll handle a few other common cases.
namely:
using a colon instead of decimal point between hours and minutes
allowing am/pm to immediately follow the time with no space
also, setting the seconds to 0 (since that was my main use case)
the resulting code would be:
var test, parts, hours, minutes, date,
d = (new Date()).getTime(),
tests = ['01.25 PM', '01:25pm', '1:25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
i = tests.length,
timeReg = /(\d+)[\.|:](\d+)\s?(\w+)/;
for(; i-- > 0;) {
test = tests[i];
parts = test.match(timeReg);
hours = /am/i.test(parts[3]) ?
function(am) {return am < 12 ? am : 0}(parseInt(parts[1], 10)) :
function(pm) {return pm < 12 ? pm + 12 : 12}(parseInt(parts[1], 10));
minutes = parseInt(parts[2], 10);
date = new Date(d);
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds(0);
console.log(test + ' => ' + date);
}

javascript conversion of yyyy-mm-dd hh:mm:ss aa help

can anybody spot any mistake in this function? .. This is a function which receives a string of type yyyy-mm-dd hh:mm:ss aa and converts to UTC and builds up a string yyyy-mm-dd hh:mm:ss.
function LocalTimetoUTC(localTime)
{
var time = localTime.split(" "); //Received :- yyyy-mm-dd hh:mm:ss aa
var yearday = time[0].split("-");
var dateTime = time[1].split(":");
var ampm = time[2];
var hours = 0;
var year = yearday[0];
var month = yearday[1]-1;
var day = yearday[2];
hours = dateTime[0];
var minutes = dateTime[1];
var seconds = dateTime[2];
/* We have to first convert it to 24 hour format
* 12:00:00 AM : 00:00:00
* 12:00:00 PM : 12:00:00
* Anytime other than 12
* 1:00:00 AM : 1:00:00
* 1:00:00 PM : 13:00:00
*/
if(ampm == "PM")
{
//If it is 12PM, adding 12 will create a problem
if(hours != 12)
{
hours +=12;
}
}
else //AM CASE
{
if(hours == 12)
{
hours = 00;
}
}
var now = new Date(year,month,day,hours,minutes,seconds);
var utcString = now.getUTCFullYear()+"-"
+(now.getUTCMonth()+1)+"-"+now.getUTCDate()+""
+now.getUTCHours()+":"+now.getUTCMinutes()+":"+now.getUTCSeconds();
return utcString;
}
Your primary problem is you are using strings in numeric operations. In addition your output formatting has some problems too. Here is an untested refactoring:-
function convertToUTCString(localTime)
{
var dateTimeComponents = localTime.split(" ");
var dateComponent = dateTimeComponents[0].split("-");
var timeComponent = dateTimeComponents[1].split(":");
var ampm = dateTimeComponents[2]
var dat = new Date(parseInt(dateComponent[0]),
parseInt(dateComponent[1]) -1,
parseInt(dateComponent[2]),
parseInt(timeComponent[0]) % 12,
parseInt(timeComponent[1]),
parseInt(timeComponent[2]) );
if (ampm == "PM") // do all locales use 'AM' / 'PM' ??
{
dat.setHours(dat.getHours() + 12);
}
function pad(val)
{
var s = val.toString();
return s.length < 2 ? "0" + s : s
}
return dat.getUTCFullYear() + "-" +
pad((dat.getUTCMonth() + 1 )) + "-" +
pad(dat.getUTCDate()) + " " +
pad(dat.getUTCHours()) + ":" +
pad(dat.getUTCMinutes()) + ":" +
pad(dat.getUTCSeconds());
}
Yyou should use Datejs for parsing dates

Categories

Resources