Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defining date in json file

I wonder to know how to set today's date in json file like we are using in js.

Is there any option to specify Date.today() in json file?

Because, json data has date object which specifies system date whenever we read the json file.

Hope, you will understand what i am trying to say.

Thanks in advance,

-Raja.

like image 277
Rajagopal 웃 Avatar asked Apr 25 '12 07:04

Rajagopal 웃


2 Answers

You can consider leveraging popular library like moment.js http://momentjs.com/

Then you can store date as YYYY-MM-DD in json and let moment handle the parsing:

var dateString = '2012-11-01';
var someday = moment(dateString);
var formattedDate = someday.format('ddd, DD MMM YYYY'); // 'Thu, 01 Nov 2012'
like image 183
250R Avatar answered Sep 17 '22 16:09

250R


JSON is a structured transport format. It does not have logic in it.

But here are options:

  1. Why not just get the date when you read the file instead?

  2. Have a server generate that JSON that includes the date at which it was generated. However, this is not ideal if you want the current date. By the time you read the file, the date generated by the server is already past.

  3. build a parser that parses a string and make it search for custom markup.

For example, special markup is contained in @{}. Get the command inside, determine the command, and execute replacement.

var jsonString = '{"data1" : "foo","date" : "@{currentdate}"}'

In this case, I'll find @{currentdate}. I should create a function corresponding to this command to replace @{currentdate} into the current date during read (in the format you want)

var parsedString = jsonString.replace(/@\{(\w+)\}/g, function(match, group) {    
    if (group === 'currentdate') {
        return new Date();
    } 
    else if (group === 'anotherCommand') {
        return 'anotherValue';
    } //and so on
});

and the result is like this:

jsonString = '{"data1" : "foo","date" : "Fri May 04 2012 01:17:07 GMT-0700 (PDT)"}'
like image 27
Joseph Avatar answered Sep 17 '22 16:09

Joseph