The application is written in express js, for robots with mongodb base I use mongoose and mongoose-ttl plugin to delete old records from the database. There is a model:

var mongoose = require('mongoose'); var ttl = require('mongoose-ttl'); var Schema = mongoose.Schema; var connection = mongoose.createConnection("mongodb://localhost/botSC"); var testSchema = new Schema({ title: String, genre: Array }); testSchema.plugin(ttl, { ttl: '1m' }); exports.Test = connection.model('Test', testSchema); 

server.js

 var Test = require('../models/test').Test; module.exports = function (passport) { router.get('/test', function (req, res, next) { new Test({title: "hello", ttl: '2s', interval: "5s"}).save(function (err, result) { console.log(result); var date = new Date(); res.send(date); }) }); return router; }; 

The following entry is stored in the database:

 { "_id": "572078bc37eac5bc1f13bf26", "title": "hello", "__ttl": "2016-04-27T08:30:54.762Z", "genre": [], "__v": 0 } 

The page displays the following date:

 "2016-04-27T08:30:52.764Z" 

But I must write down and print the following date:

 Wed Apr 27 2016 11:30:53 GMT+0300 (Финляндия (лето)) 

What could be the reason for getting the date -3h and in an incomprehensible format?

    1 answer 1

    The fact is that when sending an object from express, it converts it to a string via JSON.stringify() , which, when passing Date , returns just a string like "2016-04-27T08:30:52.764Z" as an argument. This string is a time string in the UTC time zone. To get a date in the local time zone, just pass this line to the constructor new Date(JSON.parse(date)) . JSON.parse() required (unless the client receiving the response does not convert the JSON string to an object), because in string conversion, the result will be a string containing quotes, i.e. the string will be '"2016-04-27T12:37:18.443Z"' . If the local time string needs to be delivered to the client in a formatted form, you can use the date.toString() method.

    • Clear. But why the difference is 3 hours. console.log (new Date () displays Wed Apr 27 2016 11:30:53 GMT + 0300 (Finland (summer)) and res.send (new Date ()) displays "2016-04-27T08: 30: 53.764Z" - darut
    • Z at the end of the date line indicates that the date is displayed in UTC, i.e. without offset by time zone. console.log implicitly performs toString (), which returns the time based on the time zone - NumminorihSF
    • one
      In general, there is no difference in the dates, it is the same point in time, just displayed in different time zones - NumminorihSF