0

I am a JavaScript student and came across JSONata recently.

I am creating an application where our backend requires us to send the date time field in following format: "2019-04-25T11:36:30.254Z"

I see that we can get this using JSONata by using $now() function.

I am not sure how we can use JSONata with JavaScript. Or is there a way to get date time in above format using JavaScript?

I tried below till now but not successful:

    var jsonata = require("jsonata");
    var date_now = jsonata("$now");
    console.log(date_now)

I also tried simple javascript date time objects but that does not give me the required format.

Koshur
  • 378
  • 1
  • 6
  • 20
  • Possible duplicate of [How do I output an ISO 8601 formatted string in JavaScript?](https://stackoverflow.com/questions/2573521/how-do-i-output-an-iso-8601-formatted-string-in-javascript) – str Apr 25 '19 at 11:50

3 Answers3

3

To invoke JSONata, you need to do the following...

var jsonata = require("jsonata");
var date_now = jsonata("$now()").evaluate();
console.log(date_now)

However, if you only need it to format the date to ISO8601, then using JSONata is probably a bit overkill.

Andrew Coleman
  • 1,331
  • 8
  • 8
2

You can use the native JavaScript method Date.toISOString() like in the following example:

let d = new Date()
console.log(d.toISOString())
MauriceNino
  • 6,214
  • 1
  • 23
  • 60
1

You can also use .toJSON

var jsonDate = (new Date()).toJSON();
console.log(jsonDate);

https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON

Just_lbee
  • 166
  • 1
  • 5