get today's date with parsed time in moment - javascript

I am trying to get the today's date with the time which I specified using moment js. My attempt is as below.
const time = '18:00'
const timeAndDate = moment(time)
But when I print timeAndDate it says invalid date. Is there any other way to achieve this?

const minute = 0
const hour = 18
const timeAndDate = moment().hours(hour).minutes(minute);
https://momentjs.com/docs/#/get-set/hour/

It's enough to specify the time format like second parameter in moment
const timeOfToday = moment('18:00', 'HH:mm');
console.log(timeOfToday);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Related

How can I get the ISO format for date and time in javascript?

I have two separate fields of date and time:-
const date = 2020-12-10;
const time = 22:00;
expected output:-
2020-12-10T10:00:00Z
I'm following this approach but the time in coming wrong:-
const date = DateUtil.getFullDateString(this.state.date_value);
const time = moment(this.state.time_value, ['HH.mm']).format('hh:mm a');
const momentObj = moment(date + time, 'YYYY-MM-DD HH:mm');
const dateTime = momentObj.toISOString();
the output of time is coming 18:30:00 but need to have 10:00:00
2020-12-10T18:30:00Z
You could parse date and time one by one, then add time to date and finally format as you want.
const date = '2020-12-10';
const time = '22:00';
const momentDate = moment(date).utc().startOf('day'); // utc() to avoid the offset
console.log(momentDate);
const momentTime = moment(time, 'HHmm').format('HH:mm');
console.log(momentTime);
const resultTime = momentDate.add(momentTime);
console.log(resultTime);
// Format as you want
console.log(resultTime.format('LLL'));
console.log(resultTime.format('YYYY-MM-DDThh:mm:ss.SSSA[Z]'));
console.log(resultTime.toISOString());
<script src="https://momentjs.com/downloads/moment.js"></script>
See this in order to know how to manage the UTC offset.

Moment Timezone not returning expected result

I might be doing something silly here. But essentially, the time in Lisbon right now is 12:27 PM
but the following returns 14:27 (EU central time)
const time = moment.tz("Europe/Lisbon")
const timeZone = "Europe/Lisbon"
const format = "'HH[:]mm'"
const startMoment = moment.tz(item.startTime, format, timeZone);
const endMoment = moment(item.endTime, format, timeZone);
return time.isBetween(startMoment, endMoment);
I tried several combinations and I get the wrong answer everytime. For example if I set timeZone to be "Europe/Warsaw" it returns 15:27 whereas it should be 13:27.
EDIT: const currentTime = moment().tz("Europe/London").format() returns the correct time for London. However, the return statement moment(currentTime).isBetween(startMoment, endMoment) still reads "moment(correntTime)" as the local time.
isBetween return boolean . And isBetween runs on date object. You are trying to run on time zone object. which is different from date object
const time = moment.tz("Europe/Lisbon")
const timeZone = "Europe/Lisbon"
const format = "'HH[:]mm'"
const startMoment = moment().subtract(8, 'months').tz(timeZone).format();
const endMoment = moment(new Date()).tz(timeZone).format() ;
console.log("startMoment",startMoment)
console.log("endMoment",endMoment)
console.log(moment.tz(new Date(),"Europe/Lisbon").format())
console.log(moment('2020-09-30').isBetween(startMoment, endMoment));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

How to convert a a type number in format 2300 to hours and compare to current time with Moment.js?

Given a number 1500 which is supposed to represent the time 15:00 (3pm). I'd like to convert it to a moment time and be able to compare it to the current time.
How to make this conversion and how to get the current time in that same format to be able to compare it?
const now = moment();
const time = moment('1500', 'hhmm');
const diff = moment.duration(now.diff(time));
Then to compare you can use
diff.minutes(), diff.seconds(), or diff.hours()
https://momentjs.com/docs/#/displaying/difference/
You can get the current date: moment();
Then you can set the hours and minutes: moment().set("hour", numberString.substring(0, 2)).set("minute", numberString.substring(2, 4));
Altogether that'd be:
const numberString = "1500";
const now = moment();
const nowAtNumberStringTime = moment().set("hour", numberString.substring(0, 2)).set("minute", numberString.substring(2, 4));
const difference = now.diff(nowAtNumberStringTime);
console.log(difference);

Get timezone specific date using momentjs

I am trying to calculate the time difference between two dates using moment-timezones but every time it it showing the same difference.
I am calculating the time like this:
const end_time = moment.tz(end_date, timezone);
const current_time = moment.tz(moment.tz.guess());
const difference = end_time - current_time;
let duration = moment.duration(difference, 'milliseconds');
I am getting the same duration no matter what timezone I set.
Can anybody suggest me how to get the correct difference using moment?
Use diff method, to check the duration differences between two objects
var now = moment.tz("2020-05-14 00:00:00", "Europe/Berlin");
var end = moment.tz("2016-05-14 00:00:00", "Europe/Berlin");
var diff = now.diff(end);
console.log("diff is: " + diff);
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>

Convert date and hours/minutes/seconds to correct format javascript

I got date in format '20190702' and hours/minutes/seconds in format '125657'
What is the easiest way to convert it to 07/02/2019, 12:56:57
const time = "125657";
const chuncks = str.match(/.{1,2}/g).join(":"); //12:56:57
What about date?
You can just use substr function to extract a part of string and then combine the parts to form new string
const time = "125657";
const date = "20190702";
const formattedTime = `${time.substr(0,2)}:${time.substr(2,2)}:${time.substr(4,2)}`
const formattedDate = `${date.substr(4,2)}/${date.substr(6,2)}/${date.substr(0,4)}`
console.log(`${formattedDate}, ${formattedTime}`)
The easiest is maybe this:
const time = "125657".replace(/(..?)(..)(..)/, "$1:$2:$3");
const date = "20190702".replace(/(....)(..)(..)/, "$2/$3/$1");
console.log(date, time);
The question mark in the first pattern could serve if the time string could have 5 digits instead of 6. If you are certain you always get 6 digits, you can leave it out.
You can use Moment.js to parse dates, it will accept most formats.
let momentDate = new moment.utc('20190702', 'YYYYMMDD');
console.log("Parsed date: ", momentDate);
let momentDateTime = new moment.utc('20190702125657', 'YYYYMMDDHHmmss');
console.log("Parsed date (with time): ", momentDateTime );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Use Moment.js
You provide pattern along with data.
Here, "hh" means "hours" in pattern.
"use strict";
const moment = require("moment");
console.log(moment("125652", "hhmmss").toDate());
Assuming fixed length input strings of decimal digits, you could do something like this:
const date = "20190702";
const time = "125657";
const formatted_date = date.replace(/(\d{4})(\d{2})(\d{2})/, "$3/$2/$1");
//const formatted_time = time.match(/\d{2}/g).join(":");
const formatted_time = time.replace(/(\d{2})(\d{2})(\d{2})/, "$1:$2:$3");
const formatted_date_time = `${formatted_date}, ${formatted_time}`;
console.log(formatted_date_time);
If the year was 2-digit, you could have used the same exact logic and just add a reverse, but since it's a different length, I advise you a manual composition:
const date = '20190702';
const chunks = date.match(/.{1,2}/g);
const formattedDate = [chunks[3], chunks[2], chunks[0]+chunks[1]].join('/');
console.log(formattedDate)
You may use moment.js library to format your date. In your case, the code may look like:
var time = '20190702,125657';
var formated_time = moment(time, "YYYYMMDD,HHmmss").format('DD/MM/YYYY,HH:mm:ss');

Categories