Moment.js does humanized and calendar dates, for example:
moment().calendar()
"Today at 10:17 AM"
which gets a current date object and converts to a calendar date, and
is there any way to do that in reverse? Like if I give it "Today at 10:17 AM", it returns a date object with todays date and 10:17 AM as the time?
date.js can parse human readable dates:
http://www.datejs.com/
SugarJS can also parse natural language dates:
http://sugarjs.com/dates
It can deal with stuff like:
one day before yesterday
2 days after monday
2 weeks from monday
a second ago
25 years from now
last wednesday
Also, see this related question: Is there a natural language parser for date/times in javascript?
Chrono v2
It's the only library I've found that also parses timezones.
Examples
Unfortunately, the only documented way of using is via NPM or as ES6 Module, but I found a way to use the library with the traditional script tag approach.
Non-NPM / non-module usage:
Include this script: https://www.unpkg.com/chrono-node/dist/bundle.js
Use the global variable chrono in your script (available methods here)
E.g. chrono.parseDate('Tomorrow at 4 PM PST')
Related
I'm facing an issue.
I'm saving the UTC time in my server using Java code:
DateFormat timeFormat = new SimpleDateFormat("dd-MMMM-yy HH:mm:ss");
I persist the time with this ->
time = timeFormat.format(new Date()).toString()
This is persisted as the UTC time.
Now, while displaying it in a browser, I convert it into local time :
var date = new Date(time);
convertToLocal(date).toLocaleString();
function convertToLocal(date) {
var newDate = new Date(date.getTime() +date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
console.log("Time : " + convertToLocal(date).toLocaleString())
This works fine in Chrome but in Firefox & IE , I get "Invalid Date" instead of the timestamp which I expect to see.
Please help.
The problem is that your Java code produces a date/time string that does not adhere to the
ISO 8601 format. How a JavaScript engine must deal with that is not defined (and thus differs from one browser to another).
See How to get current moment in ISO 8601 format with date, hour, and minute? for how you can change the Java code to produce a date that uses the ISO format. You can just pass the desired format (ISO) to SimpleDateFormat and configure it to mean UTC:
DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
That output should look like 2018-11-26T19:41:48Z (several variations of this are accepted). Notice the "T" and terminating "Z" (for UTC).
Once that is done, JavaScript will correctly interpret the date/time as being specified in UTC time zone, and then you only need to do the following in JavaScript, without any need of explicitly adding time zone differences:
console.log("Time : " + date.toLocaleString())
JavaScript which will take the local time zone into account in the stringification.
tl;dr
Use modern java.time classes, not terrible legacy classes.
Send a string in standard ISO 8601 format.
Instant
.now()
.truncatedTo(
ChronoUnit.SECONDS
)
.toString()
Instant.now().toString(): 2018-11-27T00:57:25Z
Flawed code
This is persisted as the UTC time.
Nope, incorrect. You are not recording a moment in UTC.
DateFormat timeFormat = new SimpleDateFormat("dd-MMMM-yy HH:mm:ss");
String time = timeFormat.format(new Date()).toString() ;
You did specify a time zone in your SimpleDateFormat class. By default that class implicitly applies the JVM’s current default time zone. So the string generated will vary at runtime.
For example, here in my current default time zone of America/Los_Angeles it is not quite 5 PM. When I run that code, I get:
26-November-18 16:57:25
That is not UTC. UTC is several hours later, after midnight tomorrow, as shown next:
Instant.now().toString(): 2018-11-27T00:57:25.389849Z
If you want whole seconds, drop the fractional second by calling truncatedTo.
Instant.now().truncatedTo( ChronoUnit.SECONDS ).toString(): 2018-11-27T00:57:25Z
java.time
You are using terrible old date-time classes that were supplanted years ago by the modern java.time classes.
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant nowInUtc = Instant.now() ; // Capture the current moment in UTC.
This Instant class is a basic building-block class of java.time. You can think of OffsetDateTime as an Instant plus a ZoneOffset. Likewise, you can think of ZonedDateTime as an Instant plus a ZoneId.
Never use LocalDateTime to track a moment, as it purposely lacks any concept of time zone or offset-from-UTC.
ISO 8601
As trincot stated in his correct Answer, date-time values are best exchanged as text in standard ISO 8601 format.
For a moment in UTC, that would be either:
2018-11-27T00:57:25.389849Z where the Z on the end means UTC, and is pronounced “Zulu”.
2018-11-27T00:57:25.389849+00:00 where the +00:00 means an offset from UTC of zero hours-minutes-seconds, or in other words, UTC itself.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 5 years ago.
I have a JavaScript Date which I want to get it into SQL Server datetime field.
The JavaScript time sent over as
Fri Sep 15 2017 00:11:44 GMT-0700 (US Mountain Standard Time)
I want it to be converted in javascript or in C#
I need the date to be like
2017-09-15 23:47:01
OR perhaps
9/15/2017 11:47:01 PM
I need to also convert it to UTC , not sure if that is easier to do in javascript or in C#
Which type of format is my code even in? "Fri Sep 15 .." ??
For UTC I was seeing code like this
var isoDate = new Date('yourdatehere').toISOString();
( I am doing .net core web api, with Angular 4 / Typescript)
As Keith said, working with dates is really hard in javascript, especially considering very different implementations across the browsers. So I will second their opinion: just use moment.js and leave everything to that library. It is really powerful. Using it you can get any date format you can possibly think of. To get "2017-09-15 23:47:01" all you need is the following (please pay attention that qualifiers are case sensitive!):
var fmt = moment(<your_js_date_if_you_have_it>).format("YYYY-MM-DD HH:mm:ss");
You can find all supported qualifiers here.
Apart from formatting this library also allows you to do a lot of manipulations with the dates, compare them, translate dates from local to UTC time zone and back, etc.
I am trying to extract different date formats from a text and later compare those dates if they belong in some time span. Let' say time span is from 1.1.2013 to 1.3.2013 . This is DD/MM/YYYY time format.
Now how can I extract different time formats from text. I have here examples of time formats.
Tue Oct 23, 2012 7:59 am
February 19th, 2013, 07:32 PM
Today, 09:22 PM
Yesterday, 09:03 AM
28 February 2013 09:38
Yesterday 16:48
8 Oct 2012 5:41:00 AM
02-18-2013, 03:17 PM
02-01-13, 12:31 PM
12.2.2013 20:43
I understand this is not a simple task to perform but any kind of suggestion can help me.
Also I am aware of this question and answers . This will benefit me later
Compare two dates with JavaScript
Also the guys on chat had this to say.
Uwe Günther
#IceD looks like you need some lib who implements that all :-)
But ih ave noe clue which one does. Better ask the Stack
IMPORTANT
I don't want jQuery in this since I can't implement it in what I am using right now. So only JS solutions for this.
You will need to normalize them to a common, comparable format, most suitably Date objects.
For some of your formats, (some browsers) will be able to Date.parse them, but for others (like "yesterday") you need to do more sophisticated parsing (up to NLP?). It would be best if you knew the format of each snippet so you can pass them to the right parsing algorithm, if not you'll need to apply some heuristics.
I have a problem with the Ext Date class seemingly returning the wrong timezone for a parsed date. Using the code below I create a date object for the 24th May, 1966 15:46 BST:
date = "1966-05-24T15:46:01+0100";
var pDate = Date.parseDate(date, "Y-m-d\\TH:i:sO", false);
I then call this:
console.log(pDate.getGMTOffset());
I am expecting to get the offset associated with the orignal date back (which is GMT + 1), but instead I get the local timezone of the browser instead. If the browser is set to a timezone far enough ahead GMT, the day portion of the date will also be rolled over (so the date will now appear as 25th May, 1966).
Does anyone know how to get around this and get Ext to recognise the correct timezone of the parsed date rather than the local browser timezone?
If this is not possible, can Ext be forced to use GMT rather than trying to interpret timezones?
I checked the parseDate() implementation in ExtJS source code and the documentation of Date in core JavaScript, the Date() constructor used by ExtJS does not support time zone information. JavaScript Date objects represent a UTC value, without the time zone. During parsing in ExtJS source code, the time zone is lost while the corresponding offset in minutes/seconds is added to the Date.
I then checked the source code of getGMTOffset() defined by ExtJS: it builds a time-zone string using the getTimezoneOffset() function defined in JavaScript.
Quoting the documentation of getTimezoneOffset():
The time-zone offset is the difference
between local time and Greenwich Mean
Time (GMT). Daylight savings time
prevents this value from being a
constant.
The time-zone is not a variable stored in the Date, it is a value that varies according to the period of the year that the Date falls in.
On my computer, with a French locale,
new Date(2010,1,20).getTimezoneOffset()
// -60
new Date(2010,9,20).getTimezoneOffset()
// -120
Edit: this behavior is not specific to Date parsing in ExtJS, the following note in the documentation of Date.parse() on Mozilla Doc Center is relevant here as well:
Note that while time zone specifiers
are used during date string parsing to
properly interpret the argument, they
do not affect the value returned,
which is always the number of
milliseconds between January 1, 1970
00:00:00 UTC and the point in time
represented by the argument.
I'm a little late but in latest ExtJS, you can pass an optional boolean to prevent the "rollover" in JS
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Date-method-parse
My two cents, because I can't really set all my time to 12:00 like Tim did. I posted on the sencha forum
I need to display dates in a couple different ways in an app built with jquery.
In some situations, I need the typical "yyyy-mm-dd hh:mma" type of formatting, with all of it's different permutations. In other cases, I need to show dates "pretty printed" similar to how StackOverflow does them:
5 seconds ago
12 minutes ago
3 hours ago
yesterday
2 days ago
My application already uses JQuery UI DatePicker which includes a formatDate() function, but as far as I can tell, there is no way to use it outside of the datepicker. I want to format dates that aren't associated with a datepicker. Is it possible to do this using DatePicker?
The DateJS library can parse dates like "12 minutes ago", but as far as I can tell, it cannot take a Date object and format strings like this. It can format the typical "yyyy-mm-dd" types of formats. This library seems pretty heavy as well.
John Resig's Pretty Dates looks like it can provide the pretty printing ("2 hours ago"), but it doesn't do the standard formatting.
Is there not a single plugin that can do all of this? Is there a way to leverage the DatePicker code so I don't have to load multiple codebases that do the same things?
http://timeago.yarp.com/
Check out prettyDate.
It's made by the same guy that does the jQuery Validation plugin.