Is there an easy way in moment.js to compare times with no date attached?
It works when I have a full ISO object with date+time, but not when it's only a time.
For example, this basic code doesn't work because, I presume, it expects a date in the value:
var time_obj = moment(active_time_format, "HH:mm:ss");
console.log(time_obj.isBefore('12:00:00'));
I understand that I can just add an arbitrary date in there, but what is the elegant way to do this?
Update:
This works from the comment below by #RichardHamilton:
var time_obj = moment(active_time_format, "HH:mm:ss");
console.log(time_obj.isBefore( moment('12:00:00', "HH:mm:ss") ));
Related
I am making a filter between two dates, Start date and End date, the filter works perfect, it brings the data but it does not bring the complete data and it is because when selecting the dates and converting them to the format, it converts them but one day remains.
This way I am converting the dates:
FiltrarPorFechas(incial, final) {
this.ListaUsuarios = [];
const IniDate = new Date(incial);
const EndDate = new Date(final);
}
associate an image with debug and conversion:
As shown in the image, the initial and final dates arrive at the method thus "2019-07-10" and "2019-07-31" but when I try to convert them it puts them one day less as shown in the image.
I have tried to use moment formatDate and it does not work, I do not understand why and I do not want to add one day.
Somebody could help me ?
You may be potentially having an issue with Timezone. You could reset the time to 00:00:00 either using moment.js or from a normal Date() object.
Now, since your aim is to compare the times, you can use the diff() available from moment.js to achieve this. Please find the sample code below
(function() {
initial = '2019-07-09';
initial_formatted = moment(new Date(`${initial} 00:00:00`));
final = '2019-07-31';
final_formatterd = moment(new Date(`${final} 00:00:00`));
console.log(initial_formatted.diff(final_formatterd, 'days'));
// moment(new Date(`${incial} 00:00:00`)).format('YYYY-MM-DD HH:mm:ss');
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js" integrity="sha256-4iQZ6BVL4qNKlQ27TExEhBN1HFPvAvAMbFavKKosSWQ=" crossorigin="anonymous"></script>
More info
Moment diff()
Date Object set() method
I am working on a script that needs to retrieve and store a timestamp from a database. The timestamp from the database is retrieved as a UTC Zulu formatted string "YYYY-MM-DDTHH:MM:SS.SSSZ". I want to store this timestamp in the format "YYYY-MM-DDTHH:MM:SS.SSS" in local time. I am currently attempting to do this with moment.js, I have had little success with ".toISOString()" and other methods.
However, I have noticed that the output from "moment(timestamp).format()" does not return the string I am expecting from what I understand so far about UTC. Here is a code example that replicates my issue:
var moment = require('moment');
var timestamp = new Date('2018-05-30T15:01:01.111Z');
console.log(timestamp);
console.log(moment(timestamp).format('YYYY-MM-DDTHH:mm:ss.sss'));
console.log(moment(timestamp).format('YYYY-MM-DDTHH:MM:SS.SSS'));
This is my output:
2018-05-30T15:01:01.111Z
2018-05-30T16:01:01.011
2018-05-30T16:05:11.111
This is my expected out:
2018-05-30T15:01:01.111Z
2018-05-30T16:01:01.111
2018-05-30T16:01:01.111
Why does the change in case from 'YYYY-MM-DDTHH:mm:ss.sss' to 'YYYY-MM-DDTHH:MM:SS.SSS' in .format() cause a different output? Is my expected output correct or have a misunderstood moment.(timestamp).format()? Lastly, is there a better way to achieve my expected output given the circumstances?
http://momentjs.com/docs/#/displaying/format/
MM is months thats why you got 2018-05-30T16:05:11.111 a 5
there is no sss but there is a SSS
you said you want in this format "YYY-MM-DDTHH:MM:SS.SSS" I assume MM you mean minutes due to your expected outcome. This is an odd way to store a date as there are no months and it's repeating seconds.
I'd suggest storing in UTC.
var timestamp = new Date('2018-05-30T15:01:01.111Z');
console.log(timestamp);
console.log(moment(timestamp).format('YYYY-MM-DDTHH:mm:ss:SSS'));
// i'd suggest UTC over formating but if you were i'd use
console.log(moment(timestamp).format('YYYY-MM-DDTHH:MM:mm:SSS'));
//2018-05-30T15:01:01.111Z
//2018-05-30T16:01:01.111
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>
Please let me know if this how you want it.
My service is returning this as date 7/14/2016 2:40 AM +00:00. How can I convert this to UTC in JS?
Tried:
new Date("7/14/2016 2:40 AM +00:00").toISOString();
In database the date has been stored as UTC so when I will display the date I want to display as Local time.
There are many ways to parse a string to produce a Date object.
One way is with the Date object itself, either by passing a string to the constructor, or by using Date.parse. However, only the ISO8601 formats are required in the ECMAScript specification. Any other input is implementation specific, and may or may not be recognized by the different JavaScript runtimes. With web browsers in particular, there are many differences in supported formats across browsers.
Additionally, the locale of the environment plays a factor in how the values are parsed. How should 1/2/2016 be parsed? January 2nd, or February 1st? You showed an example of 7/14/2016, which would be invalid input if ran in the UK (for example), where the date format is DD/MM/YYYY.
You can write custom code to split the string up into its parts, parse each part individually, and compose a result. The main problem with this approach is that the code tends to be rigid, and sometimes fragile. It should be well tested, and many edge cases need to be considered.
You can use a library, which is by far the easiest and most flexible approach (IMHO). With a good library, you can take comfort in the shared experiences of others, and in the unit tests that are (hopefully) part of the library you choose. Of course, using a library comes with several tradeoffs including increased file size, and relinquishing some degree of control. You should evaluate these tradeoffs carefully.
There are many date libraries available for JavaScript. The most popular is probably moment.js, though there are others to choose from, and some larger frameworks sometimes have similar functionality already included.
Here is an example using moment.js:
var i = "7/14/2016 2:40 AM +00:00";
var f = "M/D/YYYY h:mm A Z";
var m = moment(i, f);
var o = m.format(f); // will be in the local time, in the same format as the input
var d = m.toDate(); // if you really want a Date object
Assuming you can guarantee that format for all dates, the following code will suffice:
const datetime = '7/14/2016 2:40 PM +00:00'; // this is what your service returns
const pieces = datetime.split(/[/: ]/);
if (pieces[3] == 12) pieces[3] = 0; // fixes edge case for 12 AM/PM
const hours = pieces[5] === 'PM' ? Number(pieces[3]) + 12 : pieces[3];
const d = new Date(Date.UTC(pieces[2], pieces[0] - 1, pieces[1], hours, pieces[4]));
console.log(datetime); // prints "7/14/2016 2:40 PM +00:00"
console.log(d); // prints Date 2016-07-14T14:40:00.000Z
EDIT: There's a couple edge cases with this not handled correctly, namely 12 AM/PM, etc. but those can easily be worked around as well.
EDIT2: Accounted for that edge case.
EDIT3: As a comment stated, this will only work for UTC times. If the string you're receiving can have any offset, this will not work.
var str = "7\/15\/2016 1:00 AM +00:00".replace("+00:00","UTC");
console.log(new Date(str).toISOString()); // 2016-07-15T01:00:00.000Z
I have a simple Datetimepicker:
$('#deadline_picker').datetimepicker();
Trivially I can produce the utc / or local date string with var x= new Date(timestamp) or var x= (new Date(timestamp)).toUTCString(). And Assign it as a value to the field - $('#deadline_picker').val(x)
But for one the Datetime Picker object does not seem responsive to programmatic changes (if the Calendar has a certain date selected it will still show the same date selected and it does not appear to be timezone conscious). It is very critical for me to be able to set an exact equivalent of the Epoch time programmatically. Supposedly the datetimepicker has API methods, but the docs don't have a single example.
Edit: I'm using the copy that's referenced as being currently maintained:
https://github.com/Eonasdan/bootstrap-datetimepicker
Edit2: Apparently it has different methods from: http://www.malot.fr/bootstrap-datetimepicker/
But neither of them seem to have Timezone support.
I found that one of the commonly used ones at https://github.com/smalot/bootstrap-datetimepicker will not take (new Date).toUTCString() as an argument and is not helpful.
The one I mentioned in my question: https://github.com/Eonasdan/bootstrap-datetimepicker - Also does not appear to take (new Date()) strings of either kind, but it will take both moment() and moment.utc() objects, so in my case this worked. (Deadline is in a table row represented visually as a Timestring without seconds, year or milliseconds, to preserve datatable space).
$td = $(this).closest('tr').children('td');
var timestamp = moment.utc($td.eq(2).attr('value')*1000);
$('#deadline_picker').data("DateTimePicker").setDate(deadline);
This can be reversed with:
$('#deadline_picker').data("DateTimePicker").getDate().unix()
Can you try this?
var x= (new Date(timestamp)).toUTCString();
$('#deadline_picker').datetimepicker("update", x);
If this didnt work, try this:
$('#deadline_picker').data({date: x});
$('#deadline_picker').datetimepicker('update');
$('#deadline_picker').datetimepicker().children('input').val(x);
SOURCE
I am looking to try and calculate the number of days between 2 datepicker fields and display that value in an input field. I have searched a lot of different methods but can't seem to get any to work. I am using boostrap-datepicker.js
I have created a JS fiddle here http://jsfiddle.net/KLpq7/201/ so you can see my effort so far
My JS Is as follows
function days() {
var a = $("#datepicker_start").datepicker('getDate').getTime(),
b = $("#datepicker_end").datepicker('getDate').getTime(),
c = 24*60*60*1000,
diffDays = Math.round(Math.abs((a - b)/(c)));
$("#totaldays").val(diffDays)
}
$('.datepicker')
.datepicker({format: 'DD, dd.mm.yyyy'})
.on('changeDate', function(ev){
$(this).datepicker('hide').blur();
});
In the first part I am trying to achieve this, but it is not working!
Looking for some help...
I have modified your jsfiddle that correctly calculates the differences. One think I noticed is that you use the dd/mm/yyyy format and by default JS wants the dates as mm/dd/yyyy. It is best if you handle it the 'American' way for date difference calculations, but if you must use the 'correct' style of dd/mm/yyyy then I would recommend taking a look at the Globalize library.
function DateDiff(var date1, var date2) {
return date1 - date2;
}
Should work if you pass in two Date objects in Javascript. The result returned will be the number of milliseconds between the two, which can be quite easily converted to days or hours or weeks, etc.