JSON datetime between bash script and JavaScript - javascript

In the same spirit as discussed here, is there a recommended way to generate / parse dates from within a bash script so that it can be interfaced to Javascript Date?
To be precise, I get this strings when doing json encoding of a Javascript Date object:
2011-10-31T10:23:47.278Z
I could put together a bash hack to generate / parse that date format, but I would prefer to avoid reinventing the wheel. Does somebody have a working solution?
I am more interested in the "generating" side: I want to generate current dates from a bash script and save them in a json document (couchdb) so that they can be automatically ordered by the view engine.

The closest I am coming is this:
date -u +"%FT%T.000Z"
Which gives this output:
2011-11-03T06:43:08.000Z
I do not like that I have to put the T, the Z and the milliseconds to 0 manually (I can use %N for nanoseconds, and truncate with sed or whatever, but seems like overkill just to get millisecond precission), and I was hoping that there would be a built-in format token for date which would produce that UTC date. I assumed - wrongly it seems - that the format is common enough that it can be specified with just one format token.

JavaScript can convert many different values into dates. Not sure if that's what you mean, but for example. Your bash could generate this string: "2011/11/10 08:08:08"
When it gets to JavaScript land you can do this
var date = new Date("2011/11/10 08:08:08")
You can also do this:
var now = 1320287813362
var date = new Date(now)
More info on what Date accepts here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Other interesting info here:
What's the best way to store datetimes (timestamps) in CouchDB?

Related

Moment.js (Custom) Date Format to Rails Date Format

I was asking myself if there is an easy way to convert Moment.js (Javascript) (custom) time formats to Ruby/Rails DateTime formats, which also includes custom formats.
Example (Javascript Chrome Console):
var raw_string = "2017-02-28T01:28:27Z"
var my_custom_date_format = "YYYY-MM-DDTHH:mm:ssZ"
var parsed_string = moment(raw_string, my_custom_date_format)
console.log(parsed_string._f) # returns my_custom_date_format
I now want to send my_custom_date_format to Ruby/Rails and parse using:
IRB Console (Ruby):
require 'time'
time1 = Date.strptime("2017-02-28T01:28:27Z", "YYYY-MM-DDTHH:mm:ssZ") *
*✘ This would break because of another syntax.
time1 = Date.strptime("2017-02-28T01:28:27Z", "%Y-%m-%dT%H:%M:%SZ") **
** ✔This works, but I need a automatic converter of all possible js date formats to Ruby.
I was thinking of solving this issue maybe with RegEx, if possible or are there libraries able to convert this?
Thank you very much.

Moment.js 2 different date strings when i parse using moment gives same value

I am parsing 2 different date strings
var d1 = '2014-02-01T00:00:00.000+0530'
var d2 = '2014-02-23T00:00:00.000+0530'
when i parse them using moment
alert(moment(d1, 'YYYY-MM-dd"T"HH:mm:ss.fffffff"Z"').toDate());
alert(moment(d2, 'YYYY-MM-dd"T"HH:mm:ss.fffffff"Z"').toDate());
both of them print Sat Feb 1 2014 xxxxx
what is wrong with it??
here is the link to the fiddle i created
jsfiddle
I think your moment formatting string is causing you the problem. If I remove this, the dates do not print as the same.
http://jsfiddle.net/K5ub8/7/
EDIT: The specific issue is you are using dd for day, instead of DD. http://momentjs.com/docs/#/parsing/string-format/
Here is your fiddle fixed:
http://jsfiddle.net/K5ub8/9/
However, I am not 100% sure about the fractional seconds, I believe it is SSS instead of fffffff but I would test this if you need to cater for fractional seconds.
I should mention that if you are converting it back into a JavaScript date object anyway with toDate(), then you don't really need the moment formatting parameter as the date will be formatted in JSON Date format.
I would question why you would want to generate a moment formatted date, and then convert it back to JavaScript, a normal practice might be to receive a date in JavaScript format, then create a moment object which you can use to perform calculations and display in a nice user friendly way.
Simple answer: your format was off a bit.
http://jsfiddle.net/K5ub8/8/
After tweaking the format to be 'YYYY-MM-DDTHH:mm:ss.SSSZZ' rather than 'YYYY-MM-dd"T"HH:mm:ss.fffffff"Z"' it worked just fine. When you're trying to debug issues like this, it's always good to keep the format in a separate variable so you can use the same format that you're trying to parse out to display what you're getting. Had you done that, you would have noticed that 'YYYY-MM-dd"T"HH:mm:ss.fffffff"Z"' was messed up due to it printing out 2014-01-Fr"T"11:32:03.fffffff"-08:00". Which obviously isn't quite right.

Moment getting date attributes mistakenly

I'm trying to use MomentJS to support dates handling in my application. However, I'm facing a problem with date manipulation.
The files are loaded in this order:
<script src="/javascripts/modules/moment/moment.min.js"></script>
<script src="/javascripts/modules/moment/moment-timezone.min.js"></script>
<script src="/javascripts/modules/moment/moment-timezone-data.js"></script>
<script src="/javascripts/modules/moment/moment-with-langs.min.js"></script>
Now in somepart of my JS code I change the moment language to FR or PT.
moment.lang('fr');
Both languages validade a date as "DD/MM/YYYY" instead of american pattern. So I expect moment
to validate a date following the country date pattern passed.
Then 12/10/2014 must be: day (12), month (09), year (2014), but it is returning always american pattern instead of the correct one.
I'm getting the date properties as:
console.log("DAY: " + moment(textDate).date());
console.log("MONTH: " + moment(textDate).month());
console.log("YEAR: " + moment(textDate).year());
where textDate is my date taken from a text input.
## EDIT ##
I know I can pass the pattern to Moment. I.e:
moment(textDate, 'DD/MM/YYYY');
In the case of my application I'm using like this:
moment(textDate, '<%=lingua.general.time.pDate%>');
However, it suppose to work automatically, don't it? Of course if you already have needed language packages as well. So the previous way I mentioned before should Works, whatever.
If you don't pass any formatting arguments, moment will let your browser do the parsing (with the exception of a full ISO timestamp).
To tell moment to do the parsing, and to use the localized short date format associated with the language, pass an L as the format string:
moment(textDate, 'L')
See in the docs:
Parsing using #String+Format
The display formats. Scroll down to "Localized formats". (The parser uses the same format strings)
Also, not related to your question, but moment-with-langs already includes a copy of moment.js, so you don't need both scripts.

JSON date, display original date in the server's timezone

For example, I have a string date like this (I'm getting this from the server in json, from rails app)
s = "2013-09-01T00:00:00.000+08:00"
I would like to display it like so
01.09.2013
So I'm using moment.js library for this
moment(s).zone("+08:00").format("DD.MM.YYYY")
>> "01.09.2013"
But I don't know if needed timezone is +08:00. If I skip .zone() call, result would be wrong because my browser is in differnt timezone
moment(s).format("DD.MM.YYYY")
>"31.08.2013"
Even though in my original string I had +08:00 at the end.
So, my question is how can I extract time zone from json date string using pure javascript or moment.js library?
The simplest way I can think of is extracting the last 6 characters manually,
s.slice(s.length - 6, s.length)
> "+08:00"
But maybe there is a better approach for this task?
Just use the parseZone function, like so:
moment.parseZone(s)
Documentation is here.
Alternatively, you can use the older approach, which does the same thing:
moment(s).zone(s)

Trying to parse date using new Date(). but keep getting wrong results

I am trying to parse a date string i get from php through ajax call(which is irrelevant for now) using new Date().
however i keep getting wrong results.
My string is 2013-05-09 20:56:17
When i do
var something = new Date("2013-05-09 20:56:17");
alert(something.getMonth());
It keeps alerting 0
In my opinion for some reason new date cant parse this string.
Is there a way to specify the date format for new Date() in JS ?
My current solution is to import php's: date() and strtotime() and use them :
alert(date('m', strtotime("2013-05-09 20:56:17")));
This works however I have to use external js lib and I am pretty sure there is a better JS way to achieve that.
If you use slashes instead of hyphens, it works:
var something = new Date("2013/05/09 20:56:17");
alert(something.getMonth());
It's easy enough to replace any hyphens in a string with slashes first if you need to (say, if you were getting the date string from somewhere else):
var something = new Date("2013-05-09 20:56:17");
something = something.replace('-', '/');
It seems JavaScript's Date constructor doesn't recognize date formats with hyphens, or at least not that particular format.
Choose a different format specifier in PHP for your ajax dates. The format you expect and the format expected by the javascript are different.
var something = new Date("2013-05-09T20:56:17");
Note the 'T' which appears as a literal separator and marks the beginning of time per ISO 8601
Reference for various [browser] javascript date formats
W3 DateTime
Microsoft IE DateTime
Mozilla [Firefox] DateTime
Google DateJs
And lastly, the PHP date format specifier list:
PHP Date
PHP DateTime
Note the 'DATE_ISO8601'; but I suggest not using that at this time. Instead use 'DATE_ATOM' which may produce a date format more widely supported (comments suggest it makes iPhones happier and no issues with other browsers).
To use it in PHP:
$something = new DateTime('NOW');
echo $something->format('c');
echo $something->format(DateTime::ATOM);

Categories

Resources