Comparing two times with Moment JS - javascript

I have a problem that requires me to take two times in 12 hour format and compare them, we have moment.js included in our project and we initially thought it would be as trivial as this:
var beginningTime = moment('8:45am');
var endTime = moment('9:00am');
console.log(beginningTime.isBefore(endTime)); //false???
Fiddle: http://jsfiddle.net/KyleMuir/M4R4z/
Is there something we are missing? It feels like this shouldn't be a hard problem to solve. When we perform any moment functions on our beginningTime or endTime it simply says NAN

If you are always dealing with the time in h:mma format, you can specify it when parsing...
var beginningTime = moment('8:45am', 'h:mma');
var endTime = moment('9:00am', 'h:mma');
console.log(beginningTime.isBefore(endTime)); // true
console.log(beginningTime.toDate()); // Mon May 12 2014 08:45:00
console.log(endTime.toDate()); // Mon May 12 2014 09:00:00
<script src="https://cdn.jsdelivr.net/momentjs/2.13.0/moment.min.js"></script>
It will use today as the date, so it won't work if you are spanning different days.
JSFiddle

As per documentation you are declaring moment variable incorrectly check allowed formates
http://momentjs.com/docs/#/parsing/string/
Instead of it you can use
var beginningTime = moment({
h: 8,
s: 45
});
var endTime = moment({
h: 9,
s: 0
});
console.log(beginningTime.isBefore(endTime)); //true
<script src="https://cdn.jsdelivr.net/momentjs/2.13.0/moment.min.js"></script>

8:45am and 9:00am are invalid dates
var beginningTime = moment('8:45am');
var endTime = moment('9:00am');
console.log(beginningTime.isValid(), endTime.isValid()) // FALSE
You should use a valid format: http://momentjs.com/docs/#/parsing/string/
And they suggest that for consistent results, should use http://momentjs.com/docs/#/parsing/string-format/
Eg.
moment("2010-10-20 4:30", "YYYY-MM-DD HH:mm"); // parsed as 4:30 local time

You should just open the console and try doing this manually: moment("8:45am").toDate()
It gives you Invalid Date, which is why you're not getting expected results. Whereas "2014-05-15 08:45" gives you a date.

Related

Conver Timepicker time to utc using Timepicker (ng-bootstrap)

I am using https://valor-software.com/ngx-bootstrap/#/timepicker in my angular project.
I have one task o covert that time to UTC before I request to server.
When I select Time from timepicker value coming is as below.
Now, I have created one function to convert it to UTC using moment.js
static FormatimeSpanBeforeSubmit(date: Date | string ) {
const dateFromTimePicker = date as Date;
// Convert it to format "HH:mm:ss"
let formatedTime = moment.utc(dateFromTimePicker).format('HH:mm:ss');
// Split details in array because I want seconds as always "00"
let list = formatedTime.split(/[\s:]+/);
// Updating last value ""ss" to "00"
formatedTime = formatedTime.replace(new RegExp(list[list.length -1] + '$'), '00');
//Final value
return date ? formatedTime : null;
}
Expected Output : It should convert my time as "9:51:00"
Current Output : "10:54:00"
Please help me and guide me how can I get correct value.
Comment :
(2) As per comments from Hoài Nam I have updated my code like below and in that I am still getting 10:54:00
Please find below two images
i can't comment so i will reply you at here:
i found another solution at here https://stackoverflow.com/a/40381090/9768008
this is what i tried:
var time = 1569326290681; //Tue Sep 24 2019 18:58:10 GMT+0700 (Indochina Time)
var os = new Date().getTimezoneOffset();
var converted = new Date((time + (os * 60 * 1000)));
console.log(converted); // Tue Sep 24 2019 11:58:10 GMT+0700 (Indochina Time)
Issue was date format coming from server was wrong. So, I was getting GMT+ 6.55 instead of GMT+ 8.
Thanks for helping.
Addressed both solution. Mine as well as of #HoàiNam are correct.

Remove Seconds/ Milliseconds from Date convert to ISO String

I have a date object that I want to
remove the miliseconds/or set to 0
remove the seconds/or set to 0
Convert to ISO string
For example:
var date = new Date();
//Wed Mar 02 2016 16:54:13 GMT-0500 (EST)
var stringDate = moment(date).toISOString();
//2016-03-02T21:54:13.537Z
But what I really want in the end is
stringDate = '2016-03-02T21:54:00.000Z'
There is no need for a library, simply set the seconds and milliseconds to zero and use the built–in toISOString method:
var d = new Date();
d.setSeconds(0,0);
document.write(d.toISOString());
Note: toISOString is not supported by IE 8 and lower, there is a pollyfil on MDN.
While this is easily solvable with plain JavaScript (see RobG's answer), I wanted to show you the Moment.js solution since you tagged your questions as "momentjs":
moment().seconds(0).milliseconds(0).toISOString();
This gives you the current datetime, without seconds or milliseconds.
Working example: http://jsbin.com/bemalapuyi/edit?html,js,output
From the docs: http://momentjs.com/docs/#/get-set/
A non-library regex to do this:
new Date().toISOString().replace(/.\d+Z$/g, "Z");
This would simply trim down the unnecessary part. Rounding isn't expected with this.
A bit late here but now you can:
var date = new Date();
this obj has:
date.setMilliseconds(0);
and
date.setSeconds(0);
then call toISOString() as you do and you will be fine.
No moment or others deps.
Pure javascript solutions to trim off seconds and milliseconds (that is remove, not just set to 0). JSPerf says the second funcion is faster.
function getISOStringWithoutSecsAndMillisecs1(date) {
const dateAndTime = date.toISOString().split('T')
const time = dateAndTime[1].split(':')
return dateAndTime[0]+'T'+time[0]+':'+time[1]
}
console.log(getISOStringWithoutSecsAndMillisecs1(new Date()))
function getISOStringWithoutSecsAndMillisecs2(date) {
const dStr = date.toISOString()
return dStr.substring(0, dStr.indexOf(':', dStr.indexOf(':')+1))
}
console.log(getISOStringWithoutSecsAndMillisecs2(new Date()))
This version works for me (without using an external library):
var now = new Date();
now.setSeconds(0, 0);
var stamp = now.toISOString().replace(/T/, " ").replace(/:00.000Z/, "");
produces strings like
2020-07-25 17:45
If you want local time instead, use this variant:
var now = new Date();
now.setSeconds(0, 0);
var isoNow = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString();
var stamp = isoNow.replace(/T/, " ").replace(/:00.000Z/, "");
Luxon could be your friend
You could set the milliseconds to 0 and then suppress the milliseconds using suppressMilliseconds with Luxon.
DateTime.now().toUTC().set({ millisecond: 0 }).toISO({
suppressMilliseconds: true,
includeOffset: true,
format: 'extended',
}),
leads to e.g.
2022-05-06T14:17:26Z
You can use the startOf() method within moment.js to achieve what you want.
Here's an example:
var date = new Date();
var stringDateFull = moment(date).toISOString();
var stringDateMinuteStart = moment(date).startOf("minute").toISOString();
$("#fullDate").text(stringDateFull);
$("#startOfMinute").text(stringDateMinuteStart);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.js"></script>
<p>Full date: <span id="fullDate"></span></p>
<p>Date with cleared out seconds: <span id="startOfMinute"></span></p>
let date = new Date();
date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
I hope this works!!
To remove the seconds and milliseconds values this works for me:
const date = moment()
// Remove milliseconds
console.log(moment.utc(date).format('YYYY-MM-DDTHH:mm:ss[Z]'))
// Remove seconds and milliseconds
console.log(moment.utc(date).format('YYYY-MM-DDTHH:mm[Z]'))
We can do it using plain JS aswell but working with libraries will help you if you are working with more functionalities/checks.
You can use the moment npm module and remove the milliseconds using the split Fn.
const moment = require('moment')
const currentDate = `${moment().toISOString().split('.')[0]}Z`;
console.log(currentDate)
Refer working example here:
https://repl.it/repls/UnfinishedNormalBlock
In case for no luck just try this code
It is commonly used format in datetime in the SQL and PHP
e.g.
2022-12-25 19:13:55
console.log(new Date().toISOString().replace(/^([^T]+)T([^\.]+)(.+)/, "$1 $2") )

Date and time based json element using javascript

I have a json response like this :
{
"NO_INSPECTION": "55",
"NO_SURAT": "00055",
"DATE_OF_DESCRIPTION": "2015-12-21 03:08:24"
}
How can I convert the data in "DATE_OF_DESCRIPTION" Into date and time. Date should be dd-mm-yyy format and time should be in HH:mm format. (A sample value of DATE_OF_DESCRIPTION is 2015-12-21 03:08:24)
I have tried new Date(response.DATE_OF_DESCRIPTION); but no success. How can I achieve this?
Without the use of other libraries and assuming the output will always be zero-padded and the same length, I would do this:
var response = {
DATE_OF_DESCRIPTION: "2015-12-21 03:08:24"
}
var raw = response.DATE_OF_DESCRIPTION;
var datePart = raw.split(' ')[0];
var timePart = raw.split(' ')[1];
var year = datePart.substring(0, 4);
var month = datePart.substring(5, 7);
var day = datePart.substring(8, 10);
var hours = timePart.substring(0, 2);
var minutes = timePart.substring(3, 5);
// NOTE: Month is 0 indexed
var date = new Date(year, month - 1, day);
var dateTime = new Date(year, month - 1, day, hours, minutes);
console.log(date);
console.log(dateTime);
This gives the output
Mon Dec 21 2015 00:00:00 GMT+1000 (E. Australia Standard Time)
Mon Dec 21 2015 03:08:00 GMT+1000 (E. Australia Standard Time)
(I'm from Australia, so your timezone will vary)
JavaScript has a fixed date format and you can change it, thus the Date object won't help you this time. As I see it, you want to split that date, so it's pretty easy if you provide it in this format "dd-mm-yyy HH:mm":
response.DATE_OF_DESCRIPTION = response.DATE_OF_DESCRIPTION.split(" "); // date and time are separated by an space
var date = response.DATE_OF_DESCRIPTION[0];
var time = response.DATE_OF_DESCRIPTION[1];
BTW, if you want to parse a date in a specified format, why don't you use any library for that? Many of them are almost as reliable and fast as native methods. Give them a try ;)
You could also format the date, so it fits the JS specs but, why reinvent the wheel? Libraries will do this for you and you'll get optimal cross-browser results!
I've googled "javascript date parsing library" and this is what I've found:
http://momentjs.com/ <--- I think that's what you're looking for!

Unix offset with fullCalendar difference

I want to place a check when I'm getting a momentjs instance through fullCalendar.
I'm at the eventRender callback
var calendar = $('#calendar').fullCalendar('getCalendar');
var atime = calendar.moment();
var atime_h = atime.format("HH:mm");
atime = atime.unix();
var start = calendar.moment(event.start);
var start_u = start.unix();
var start_h = start.format("HH:mm");
console.log(atime);
console.log(atime_h);
console.log(start_u);
console.log(start_h);
Now what that logs is this:
1408024477
15:54
1407888000
00:00
1408024477 == Thu Aug 14 15:54:37 2014 == is correct
But 1407888000 == Wed Aug 13 02:00:00 2014, where I would expect 00:00 instead of 02:00
So there's a difference between the event .unix()/format.() and the moment I created.
Anyone got a clue what's going on?
Edit:
So what happens is that if I create two new moments: moment() and a moment().utc(), I get the same timestamp for both. But when I then display them, there is a difference of two hours.
The .utc one returns two hours in the past, the one without the correct one for me. The timestamp is not two hours back.
But with the event.start (which has _isUTC=true, the timestamp is two hours in the future (!), and it displays it correct when formatted.
So maybe I need to have my event.start to be not UTC and two hours back somehow?
Edit by request in comment, this is what I use now:
var start = calendar.moment(event.start);
console.log(start);
start_utc = new Date(start.year(), start.month(), start.date(), start.hour(), start.minute(), start.second());
var start = calendar.moment(start_utc);
console.log(start);
Try converting your event.start date to utc first, here's how to do it in vanilla js:
start_utc = new Date(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds());
Then you can call .unix() on it and it should give you the expected timestamp.

Javascript convert seconds to a date object

How can I convert seconds into a datetime object in javascript.
Examples:
1.3308313703571
1.6324722385401
This is from a series of points and when they occurred. I understand 1.23323 more then seconds, but I can not change the value, being pulled from an api.
You can try like this:
function toDateTime(secs) {
var t = new Date(1970, 0, 1); // Epoch
t.setSeconds(secs);
return t;
}
Info on epoch date.
You can pass unix timestamp milliseconds as an argument to the Date constructor:
const secs = 30;
const output = new Date(secs * 1000);
console.log(output);
#UVM's answer is helpful, but slightly incomplete if you're dealing with timezones (i.e. UTC vs local time). With timezones, start with UTC using Date.UTC and Date.setUTCSeconds to get a true UTC date and time.
function toDateTime(secs) {
var t = new Date(Date.UTC(1970, 0, 1)); // Epoch
t.setUTCSeconds(secs);
return t;
}
You can then use a library like Moment to convert/format it to a local timezone.
your example values have a decimal.. looking like you are trying to convert 1.something seconds into a date..
Meanwhile check this example here on the correct seconds to date conversion.. you could view their js sources.
The question seems to have already been answered but this may be helpful for those attempting to do something similar to ruby's Time.at() method.
function formatDateTime(input){
var epoch = new Date(0);
epoch.setSeconds(parseInt(input));
var date = epoch.toISOString();
date = date.replace('T', ' ');
return date.split('.')[0].split(' ')[0] + ' ' + epoch.toLocaleTimeString().split(' ')[0];
};
I dunno how it be 10 years ago, but now it can solve just doing next:
let sec = 1628618888939
let time = new Date(sec)
let normalDate = new Date(sec).toLocaleString('en-GB',{timeZone:'UTC'})
time: "Tue Aug 10 2021 21:08:08 GMT+0300 (Eastern European Summer Time)"
normalDate: "10/08/2021, 18:08:08"
If in the future u will have problems like this, I can advise read about functions that relate to your question, and solution will come.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Categories

Resources