I am trying to provide a default value for a TimePicker object. But the that value I have is a string e.g "12:00 PM" And the picker needs a Date object.
I tried parsing the time directly into a Date object like shown below, but it does not work
let startTime = new Date("12:00 PM");
How can i convert this time string into a Date object so that i can provide the default value to the TimePicker.
Ive been able to create a function that can do the conversion, since I did not find any solution to this.
const dateFromTime = ({ timeString }) => {
const dateTime = new Date();
let timeHours = parseInt(timeString.substring(0, 2));
let timeMinutes = parseInt(timeString.substring(3, 5));
let timeAMPM = timeString.substring(6,
if (timeAMPM === "PM") {
timeHours += 12;
dateTime.setHours( timeHours, timeMinutes, 0, 0);
return dateTime;
}
const dateTime = dateFromTime({ timeString: "12:00 PM" });
This get the current date and time and instead sets the time to the specified time. and returns that
For any improvements, please suggest the right way to do this.
HTML:
<input id="appt-time" type="time" name="appt-time" value="13:30">
JS
const timeFrom12hto24h = time12h => {
const [time, meridiem] = time12h.split(" ");
let [hours, minutes] = time.split(":");
if (hours === "12") hours = "00";
if (meridiem === "PM") hours = parseInt(hours, 10) + 12;
return {hours, minutes}
};
const getMyObjectTime= timeFrom12hto24h('12:00 PM');
// apply the time to the HTML element
document.getElementById("appt-time").value = getMyObjectTime.hours + ':' + getMyObjectTime.minutes;
// one way to generate the needed time object
const dateInMiliseconds = new Date().setHours(getMyObjectTime.hours, getMyObjectTime.minutes, 0)
console.log(dateInMiliseconds);
In case there is moment.js already used in the project it would be like this:
HTML:
<input id="appt-time" type="time" name="appt-time" value="13:30">
JS:
// apply the time to the HTML element
document.getElementById("appt-time").value = moment("01:00 PM", 'hh:mm A').format('HH:mm')
// one way to generate the needed time object
let [hour, minutes] = moment("01:00 PM", 'hh:mm A').format('HH,mm').split(',');
const dateInMiliseconds = new Date().setHours(hour,minutes, 0)
console.log(dateInMiliseconds);
You just need to give the correct format to the Date object.
solution 1
If you don't care about date then you can simply convert like this.
let startTime = new Date(`2022/01/01 12:00 PM`);
solution 2
If you need today's date then you can simply convert like this.
let startTime = new Date(`${new Date().toDateString()} 12:00 PM`)
I used date-and-time package to format current time. It's worked for me.
npm install date-and-time
Controller
const date = require("date-and-time");
const now = new Date();
const startTime = date.format(now, "HH:mm:ss");
Related
I want to check if the middle date is between the right and left date, how can I accomplish this in Javascript, they are an ISO String.
From 2021-01-30T05:00:00.000Z <-> Date 2021-01-31T22:18:46Z <-> To 2021-01-31T05:00:00.000Z
How can I verify 2021-01-31T22:18:46Z is between 2021-01-30T05:00:00.000Z and 2021-01-31T05:00:00.000Z
Two easy options...
Compare the date strings lexicographically
const From = "2021-01-30T05:00:00.000Z"
const date = "2021-01-31T22:18:46Z"
const To = "2021-01-31T05:00:00.000Z"
if (From.localeCompare(date) <= 0 && To.localeCompare(date) >= 0) {
console.log("Date is in range")
} else {
console.log("Date is not in range")
}
or parse the date strings as Date instances or timestamps and compare them numerically
const From = new Date("2021-01-30T05:00:00.000Z")
const date = new Date("2021-01-31T22:18:46Z")
const To = new Date("2021-01-31T05:00:00.000Z")
if (From <= date && To >= date) {
console.log("Date is in range")
} else {
console.log("Date is not in range")
}
Note: If you're using Typescript, it doesn't like comparing Date instances numerically. Compare Date.prototype.valueOf() or Date.prototype.getTime() instead
The main idea is we just need to compare Date only.
However, if you use .moment or new Date() to parse the date-time UTC, you will recognize an interesting that
moment("2021-01-31T22:18:46Z").format("YYYY-MM-DD") // "2021-02-01"
new Date("2021-01-31T22:18:46Z") // Mon Feb 01 2021 05:18:46 GMT+0700 (Indochina Time)
So if the compareDate like 2021-01-31T05:00:00.000Z, then you will get the expected result.
const fromDate = moment("2021-01-30T05:00:00.000Z").format("YYYY-MM-DD");
const conpareDate = moment("2021-01-31T05:00:00.000Z").format("YYYY-MM-DD");
const toDate = moment("2021-01-31T05:00:00.000Z").format("YYYY-MM-DD");
console.log({fromDate, conpareDate, toDate});
console.log(moment(conpareDate).isBetween(fromDate, toDate, undefined, '(]'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
If you still want to compare exactly the date, you can achieve it in this way (But to be honest, It's not recommended).
const fromDate = '2021-01-30T05:00:00.000Z'.split('-');
const conpareDate = '2021-01-31T22:18:46Z'.split('-');
const toDate = '2021-01-31T05:00:00.000Z'.split('-');
const partStringToInt = (str) => parseInt(str, 10);
const compareBetween = (a, b, c) => partStringToInt(a) <= partStringToInt(b) && partStringToInt(b) <= partStringToInt(c);
const result = compareBetween(fromDate[0], conpareDate[0], toDate[0]) // Year
&& compareBetween(fromDate[1], conpareDate[1], toDate[1]) // Month
&& compareBetween(fromDate[2].substring(0, 2), conpareDate[2].substring(0, 2), toDate[2].substring(0, 2)); // Day
console.log(result);
function getElapsedMS(strOfD1, strOfD2) {
var d1 = new Date(strOfD1);
var d2 = new Date(strOfD2);
return d1-d2;
}
var d2d1 = getElapsedMS("2021-01-31T22:18:46Z", "2021-01-30T05:00:00.000Z");
var d2d3 = getElapsedMS("2021-01-31T22:18:46Z", "2021-01-31T05:00:00.000Z");
if (d2d1 * d2d3 < 0) { // can have more consideration to avoid overflow
//d2 is between d1 and d3
}
Unix timestamp
Each date can be represented as milliseconds since epoch, so we can convert each date to milliseconds and compare whether one date is after another or not.
Example:
const dateA = new Date("2021-01-30T05:00:00.000Z");
const dateB = new Date("2021-01-31T05:00:00.000Z");
const dateC = new Date("2021-01-31T22:18:46Z");
// We use getTime() method to get the date as milliseconds since epoch
const isDateCBetweenAandB = dateA.getTime() <= dateC.getTime() && dateC.getTime() <= dateB.getTime();
console.log(isDateCBetweenAandB);
You can compare its unix timestamp try it:
Date.parse('2021-01-31T22:18:46Z');
I have a list of array exdate which has some date. I want to exclude those dates and suggest the next available date from today. Date should not be random.
const exdate = ["24/08/2020", "8/8/2020"] //dates needs to be excluded [DD/MM/YYYY]
The newly generated date would be "25/08/2020" which is the closest one and not in the array.
This post has a question that is generating a random date using math.random function but my scenario is different.
Iterate inside a while loop and check if exdate contains the current date. If it doesnt contain the date, add 1 day to the current date and check it again. If the current date is not present inside the exdate array, exit the while loop and print the value.
A thing you might consider: What is the expected format of your dates? You should make sure it stays consistent. e.g. dont use leading 0s in front of months. My answer should point you into the right direction.
exdate = ['24/8/2020', '8/8/2020'];
let currDate = new Date();
let dd = currDate.getDate();
let mm = currDate.getMonth() + 1;
let y = currDate.getFullYear();
let dateFormat = dd + '/' + mm + '/' + y;
while (true) {
dd = currDate.getDate();
mm = currDate.getMonth() + 1;
y = currDate.getFullYear();
dateFormat = dd + '/' + mm + '/' + y;
if (!exdate.includes(dateFormat)) break;
currDate.setDate(currDate.getDate() + 1);
}
console.log(dateFormat);
I think this code does what you are after and is quite simple:
import moment from "moment";
// Constants
const dateFormat = 'DD/MM/YYYY'
// Utils
const strToDate = (date) => moment(date, dateFormat)
const dateToStr = (date) => date.format(dateFormat)
const sortByMoment = (a, b) => b.diff(a)
const incrementDate = (date) => date.add(1, 'day')
const isToday = (date) => moment().isSame(date, 'day')
// Data
const exdate = ["17/08/2020", "24/08/2020", "8/8/2020"];
// Implementation
const sortNewestToOldest = (data) => data
.map(strToDate)
.sort(sortByMoment)
const nextAvailableDate = ([head]) => isToday(head) ? [dateToStr(incrementDate(head))] : [dateToStr(moment())]
nextAvailableDate check if todays date is in the exdate list, if yes return tomorrow, else return today. If you also had future dates in there that you need to accomodate for you could expand isToday to be isTodayOrInTheFuture. The moment functions you would need can all be found here.
I am using Node.JS and the excellent Moment library. I have a function that needs to generate an agenda of future dates (like an appointment system)
I have two timestamps representing the start and end of a period of time.
I want to create an array of date/times between these two times, dependent on a specific day and time of that day.
An example would be:
START DATE: 2019-01-26 15:00:01 (Saturday)
END DATE: 2019-02-23 15:00:00 (also a Saturday)
WE NEED: EVERY SATURDAY # 1500
EXPECTED ARRAY:
2019-02-02 15:00:00
2019-02-09 15:00:00
2019-02-16 15:00:00
2019-02-23 15:00:00
Please note: The start is not included in the array because it is later (by one second) than what we are looking for.
Any idea on how to accomplish this in Node?
const moment = require('moment')
const formatDate = date => moment(date).format('MMMM Do YYYY, h:mm:ss a')
const START_DATE = '2019-01-26 15:00:00'
const END_DATE = '2019-02-23 15:00:00'
let current = formatDate(START_DATE)
const end = formatDate(END_DATE)
let days = 7
let result = []
while (current > end) {
current = moment(START_DATE).add(days, 'days')
current = formatDate(current)
result.push(current)
days += 7
}
result.push(end)
result.forEach(date=>console.log(date))
import moment from 'moment';
const getDaysBetween = (startDate, endDate, day, time) => {
// Define a first day of result
let firstDay = moment(startDate)
.day(day)
.set('hour', time.match(/[\d]+(?=:)/g)[0])
.set('minutes', time.match(/(?<=:)[\d]+/g)[0])
.set('seconds', 0);
let resultDates = [ firstDay ];
// Add the rest
let weekBetweenThese = endDate.diff(firstDay, 'week');
Array(weekBetweenThese).fill({}).forEach((d, i) => {
resultDates.push(moment(firstDay).add(i + 1, 'weeks'))
});
// Filter out somecase that result day match with startDate & endDate but time condition goes wrong
resultDates = resultDates.filter(resultDate =>
startDate <= resultDate &&
resultDate <= endDate
);
return resultDates.map(resultDate => resultDate.toDate());
// return resultDates; // Return array of moment date.
};
console.log(
getDaysBetween(
moment('2019-01-26 15:00:01'),
moment('2019-02-23 15:00:00'),
'Saturday', '15:00'
)
)
https://codesandbox.io/s/wkpz72mo9w
I need difference of two timestamp in seconds. But when calculate it gave wrongly. How to calculate the seconds from difference of two timestamp? Thanks in advance.
Here,
First timestamp = 20180104113612
Second timestamp = 20180104113954
Difference = First timestamp - Second timestamp
It results as 342. But actually it should be 222. So please anyone help to find the difference in seconds?
You need to parse out year, month, day, hour, minutes and seconds from your date and create a date object and then subtract both dates to get the difference.
var firstTimestamp = 20180104113612,
secondTimestamp = 20180104113954,
getDate = (time) => {
time = time.toString();
var year = time.substring(0,4),
month = time.substring(4,6),
day = time.substring(6,8),
hour = time.substring(8,10),
minutes = time.substring(10,12),
seconds = time.substring(12,14);
return new Date(year, month, day, hour, minutes, seconds);
},
getTimeDifference = (firstTime, secondTime) => {
return Math.floor((getDate(secondTime) - getDate(firstTime))/1000);
};
console.log(getTimeDifference(firstTimestamp, secondTimestamp));
Try this
let startDate = new Date();
let endDate = new Date();
let differenceInSecond = (endDate - startDate) / 1000; //since it's originally in milliseconds
first you have to format your date in proper format something like this. "2018-01-04T11:36:12";
for formatting you can use make some function like this
function getFormat(dateString) {
var txt = dateString.slice(0, 4)
+ "-"
+ dateString.slice(4, 6)
+ "-"
+dateString.slice(6,8)
+"T"
+dateString.slice(8,10)
+":"
+dateString.slice(10,12)
+":"
+dateString.slice(12,14);
return txt;
}
and then convert it into javascript Date object.
const First_timestamp = 20180104113612;
const Second_timestamp = 20180104113954;
const FirstDate = new Date(getFormat(First_timestamp.toString()));
const SecondDate = new Date(getFormat(Second_timestamp.toString()));
const TimeDiffInSeconds = (SecondDate.getTime() - FirstDate.getTime()) / 1000;
I have four fields in a form, some containing an initial date and the end date (dd / mm / yyyy) and the others contain the start time and the end time (hh: ss).
The value of these fields I use to get the date and time with moment.js such as this:
initialdate = moment( $('input#start_date').val(), 'DD/MM/YYYY' );
start_time = moment( $('input#start_time').val(), 'HH:mm');
enddate = moment( $('input#enddate').val(), 'DD/MM/YYYY' );
end_time = moment( $('input#end_time').val(), 'HH:mm');
What I intend is to then get the difference in seconds between the two dates, concatenating the starting date and time and the ending date and time. I have tried to do this, but to no avail:
start = initialdate + start_time;
end = enddate + end_time;
tracker = moment.duration( end.diff(start) ).asSeconds();
Concatenate the date and time strings and parse them as one, e.g.
var date = '23/02/2017';
var time = '15:42';
var dateTime = moment(date + ' ' + time, 'DD/MM/YYYY HH:mm');
console.log(dateTime.format('YYYY-MM-DD HH:mm'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>
The fail is trying on concatenate the values, test with something like this:
let initialdate = '2016-10-01';
let start_time = '19:04:10';
let enddate = '2016-10-01';
let end_time = '19:04:20';
let datetimeA = moment(initialdate + " " + start_time);
let datetimeB = moment(enddate + " " + end_time);
console.log(datetimeA.format());
console.log(datetimeB.format());
let datetimeC = datetimeB.diff(datetimeA, 'seconds');
console.log(datetimeC);
[2021] Most elegant solution is:
/* `date` and `time` are instances of Moment */
date = date.set({
hour: time.get('hour'),
minute: time.get('minute'),
second: 0,
millisecond: 0,
});
A much cleaner solution IMO is to use moment's hour and minute getters and setters.
let a = moment()
let b = moment().add(3, 'hour').add(37, 'minute') //b is the time portion
a.hour(b.hour()).minute(b.minute())
Simply use this function
function getCombinedDateObject(date, time) {
let calculatedDateString = '';
if (date && time) {
let utcDate = moment.utc(date);
let utcTime = moment.utc(time);
calculatedDateString = moment(`${utcDate.format('YYYY-MM-DD')} ${utcTime.format("HH:mm:ss z")}`);
}
let finalDateTime = new Date(calculatedDateString);
if (isNaN(finalDateTime.getTime()))
return null;
else
return finalDateTime;
}
My answer is simple,
I just change the time of date as following:
const date = new Date(myDate)
const time = new Date(myTime)
date.setHours(time.getHours())
date.setMinutes(time.getMinutes())