I have an input time setting which is like this.
{
"effectiveFrom": "2022-03-24 06:28",
}
I need to convert the same to UTC format which is like this
{
"effective_from": "2022-03-24T00:58:00.000Z",
}
How can i do that I am using this code over here but this is not working as expected any help is great.
new Date(ctx.params.dateTime);
CodePudding user response:
When you parse the date string using new Date(ctx.params.dateTime)
you will get a Date object in return.
To get the UTC string as output, you can call the toISOString()
method on that object.
const dt = new Date('2022-03-24 06:28')
const isoString = dt.toISOString()
console.log(isoString)
CodePudding user response:
The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".
Source: MDN Web Docs
console.log(new Date('2022-03-24 06:28').toISOString())
.toISOString()
will give you the format you are requesting. But you can't perform any date operations on that since the output you get is a string.
I just created a simple node file and check where you are doing wrong.
var http = require("http");
const Sequelize = require("sequelize");
const sequelize = new Sequelize("test", "postgres", "postgres", {
host: "localhost",
port: 5431,
dialect: "postgres",
options: {
encrypt: false,
},
});
const UserProfile = sequelize.define("userProfile", {
name: {
type: Sequelize.STRING,
},
DateTimeCol: {
type: Sequelize.DATE,
},
TimeCol: {
type: Sequelize.TIME,
},
});
userProfile.sync().then(() => {
userProfile.create({
name: "Test User",
DateTimeCol: "2022-03-24T08:00:00.000Z",
TimeCol: "13:00",
});
userProfile.findAll().then((data) => console.log("user response", data));
});
var server = http.createServer(function (req, res) {
res.writeHead(200);
res.end();
});
server.listen(8085);
By the way, I have used sequelize and postgres for testing.