3

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.

Community
  • 1
  • 1
blueFast
  • 41,341
  • 63
  • 198
  • 344

2 Answers2

11

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.

blueFast
  • 41,341
  • 63
  • 198
  • 344
  • 5
    You can get actual nanoseconds truncated with the following (tested on CentOS 6.4): `date -u +"%FT%T.%3NZ"` That appends the current nanoseconds truncated to three characters. Here's some example output: `2015-05-11T19:18:54.021Z` – Dylan Northrup May 11 '15 at 19:21
1

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?

Community
  • 1
  • 1
Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50
  • I understand that your suggested format `2011/11/10 08:08:08` is easy to generate and sorts ok. But to tell you the truth, I am not sure I would be covering all corner cases (summer / winter time, timezones, and whatnot) with that format. I would really prefer to stick to the format `2011-10-31T10:23:47.278Z`, which gives me peace of mind. And the reason I ask is that I would like to use a pre-existing format string to `date` (or similar tool), so that I am not reinventing the wheel here. – blueFast Nov 03 '11 at 06:35