MomentJS: Display formatted range between two arbitrary dates - javascript

I have two arbitrary dates that I would like to compare using MomentJS. By "arbitrary," I mean that neither of them are now (i.e. moment()).
I would like to display both of these dates as a nicely-formatted string based on the difference between them. For example, if the difference between them is just a few hours, I'd rather display something like "5 am to 8am", rather than "1/1/2018 5:00am to 1/1/2018 8:00am".
Put more succinctly, I'm trying to see if moment can determine which fields are equivalent, and based on this, format the time range as a string without any redundant information.
Is there a way to do this using standard functions in MomentJS?
Here's what I understand so far:
The functions such as toNow(), fromNow(), to(), and from() all provide relative time ranges, but these are in reference to now. What I'm looking for is this same interface, but without referencing now.
I believe that my options are either to:
Use one of the aforementioned functions to compare the two dates, drop the suffix, and display something like "1/1/2018 5:00am + 3 hours", OR
Use a duration to compare the dates, and add custom code to determine equivalent quantities, and set the format accordingly. E.g. if years, months, weeks, and days are equivalent, format each timestamp as "h:mm:ss a".
The output of the second option would be much more desirable. Essentially, I'm trying to implement this option using MomentJS and as little custom code as possible.

It looks like this is handled externally by a plugin called Twix.

Related

Using moment.js, how to display the current date format for the user?

Given a text field, I want to have a suitable placeholder. A typical placeholder will be something like: "mm/dd/yyyy".
However, I would like to use locale-aware dates using moment.js.
This means that I will be specifying "l" as the moment.js date format, howe do I determine the date format that moment.js will be using in this case?
The user will not understand what "l" means, so using this value in the placeholder text makes very little sense.
Specifically, I am hoping to be able to access something like moment's internal "defaultLongDateFormat". (Though that is merely a default - moment.js probably updates it or has some other mapping at runtime for locale-aware date formats - I would like to access that mapping.)
EDIT:
There are multiple downvotes (who aren't explaining why they're downvoting it).
I think this is because they arent' understanding the question, so here are some examples:
I want a function such that:
getFormat("l") -> "mm/dd/yyyy", or equivalent for the US locales.
getFormat("l") -> "dd/mm/yyyy", or equivalent, for the AU locales.
I do not want to format a given date, or to parse a given date - I merely want to determine it's user-friendly format given an arbitruary moment.js format, specifically, for 'l'.
I don't think it's exposed nicely, but if the browser has its language configured correctly you can do something like this:
var lang = navigator.languages ? navigator.languages : navigator.language;
moment().locale(lang).localeData()._longDateFormat['L']
Languages behave slightly differently depending on which browser you're using, so don't know how reliable this is.
Follow up to Adam R's answer:
Seems to have been exposed by now:
localeData.longDateFormat(dateFormat);
returns the full format of abbreviated date-time formats LT, L, LL and so on
(source: http://momentjs.com/docs/)
Get the currently used locale data by moment.localeData()

How to represent time in JavaScript?

HTML5 form input element provides a way to enter only time. What is the best way to represent that time then in a JavaScript object which could be manipulated in a similar way one can manipulate datetime objects with moment.js? If I use moment.js to parse only time, like moment('12:13:14', 'HH:mm:ss'), it is added current date to the value. So it is not possible to know that in fact the object represents only time. So if you later want to work with the object, you do not know if that is date or time.

Convert timestamp with specified offset for timezone with Date();

I've been digging through as many things as I can find, and I can't seem to find what it is I am looking for, so I am coming to the conclusion that I either don't know what I am looking for or its not possible. Either way..
What I am trying to achieve is taking a timestamp example: 1373439600000 and a given offset of -12 to 12 (is that correct, as far as range goes?) so I can then take that timestamp above subtract from it accordingly, and pass that new timestamp to the Date() function so I can then manipulate it for human readable display.
The offset is two part, It is user specified in one instance while in the other it is going to default to the local getTimezoneOffset() if not specified. So trying to figure out how to take that range and work with that. To do everything accordingly.
Ideas? Am I even approaching this in a correct manor?
The timestamps I am working with are already UTC, not sure of that makes a difference.
The JavaScript Date type has many problems, but one of its major quirks is that it only understands two time zones - UTC, or Local. It uses UTC internally and in certain properties and functions like .toUTCString(), but otherwise it uses the local time zone.
Many browsers will accept an offset when parsing a Date from a string, but that will just be used to set the UTC time. Anything on the way out will be converted back to the local time zone again.
Fortunately, there are some great libraries out there for working around these problems. Moment.js is perfectly suited for this. Here is an example of what you might be looking for:
moment(1373439600000).zone(8).format("YYYY-MM-DD HH:mm:ss Z")
// output: "2013-07-09 23:00:00 -08:00"
Of course, you can format as needed, or pass in a more complex zone offset like "+05:30". And if you need to use an actual IANA time zone, there is the moment-timezone companion project, which you could do something like this:
moment(1373439600000).tz('America/New_York').format("YYYY-MM-DD HH:mm:ss Z")
// output: "2013-07-10 03:00:00 -04:00"
Unfortunately the Date object does not provide may facilities for working with timezones. If you have the offset though, you should be able to compute the offset in milliseconds. Then you can add (subtract?) that value to your timestamp and use it to construct the appropriate Date.
Does that help?

Localization and Time Format

We know that different locales use different date and number formats, but what about time formats? There are certainly fewer ways to format time values than date values.
I have a field in a web application that accepts a time value as free text, hour and minute only. Suppose that the field allows only one of the following formats for all locales.
23:59
2359
12:59p
p12:59
Note that "p" and ":" are customizable for each locale.
Would this be too much restriction for a localizable application supporting non-English locales? I'm asking since there's no built-in parser for time values in JavaScript and it seems that most projects build their own mini parser.
Maybe what you are looking for is JQuery Time Picker. I don't think any of these plugins support JQuery Regional scripts, but at least it should be easier to create your own localized settings instead building a parser...
If you still want to build a parser, go for it although trying to support all possible combination (like "6:40", "06:40", "6:40 P.M.") would be at least problematic. As Stefan mentioned, it is easier to do just some kind of drop-down boxes (personally I hate them as they require clicking). Otherwise you may create to text fields: one for hour part and the second one for minutes and add drop-down for selecting AM/PM conditionally (that is if preferred format for this locale is 12 hours).
What about time zones? I'd recommend that the user time zone would be in use, but the time would be then converted to UTC and stored as such internally...

Multiple date compare in javascript

I am trying to validate, get and compare 2 dates.
The dates are coming from 2 text inputs and are currently formatted as the following example: 17/01/2011 00:00
How do I convert that string to a date using the Date object?
I'm trying to validate it under these terms:
Date must be in the correct format (17/01/2011 00:00)
Date must be in the future (How do I do that considering JS runs on Local and date can be set incorrectly on the user's machine?
First date must be before second date. (it's a from_date -> to_date input).
Can you please assist?
Thanks,
A slightly different approach,
If it is not too late, you can enforce the validity of the date by providing a date / time selection control that will output the date in the format that you required (There should be quite a lot of them out there, see this or this for some. In this way, you don't have to rely on the user to input the date in a textbox where they can input whatever they want. If this is not possible, you can try looking at the input masking that might help the user input the date more accurately in a textbox format, for example see: this or even this that will allow you to input string like "today", "2 weeks from now", etc. This will increase the usability aspect of the form.
You might have to revalidate the date on the server side for this. It's always a good idea to double check user inputs both at client side and again in server side. But for client side validation, you can try the datejs libray i mentioned above or create one as per suggestion from Stefanos.
Already answered this in #2.
Hope that helps.
As for the format validation you can use a regex to do it.
To get the current time you need to request the data from a server. One option is from the one your users get the web pages using a backing language (php, java, ...). One other option is to request the time from a time server with an http request. The answer could be simle text or an XML, or you may need to communicate with another protocol, like SOAP.
To compare the 2 dates you can convert them to milliseconds and then simply compare the values. Also the JavaScript object Date can be helpful for conversions and comparisons.
You cannot manipulate times and dates without knowing the time zone.
If a string representation of a date does not include the GMT offset, you have to guess the time-zone, unless you add a rule to account for it, or only want the date to be within a day or so accurate.

Categories

Resources