I don't have the complete picture of your setup, but yes, loopback does convert to UTC from local time when saving dates. If you look in the mysql connector, you'll find the following function that builds up the datetime
string from UTC values of the given date:
function dateToMysql(val) {
return val.getUTCFullYear() + '-' +
fillZeros(val.getUTCMonth() + 1) + '-' +
fillZeros(val.getUTCDate()) + ' ' +
fillZeros(val.getUTCHours()) + ':' +
fillZeros(val.getUTCMinutes()) + ':' +
fillZeros(val.getUTCSeconds());
function fillZeros(v) {
return v < 10 ? '0' + v : v;
}
}
It should, however, restore the date to local time on load because it initializes the javascript Date
object from the stored string, which will convert to local time:
val = new Date(val.toString().replace(/GMT.*$/, 'GMT'));
Your best option is probably to use operation hooks and manipulate the data as it flows in/out of your model. For example, you could format the date however you want as the data gets loaded from the data store:
Order.observe("loaded", (ctx, next) => {
if (ctx.data) {
ctx.data.delivery_date_formatted = tzFormat(ctx.data.delivery_date);
}
next();
});
You can also approach this from the other direction and manipulate the data that's being persisted. You can't really prevent loopback from storing the date as UTC, but you could add or remove the timezone offset so once it gets stripped it by loopback connector, it will persist a string with your local time (VERY hacky, I wouldn't recommend it). Example:
Order.observe("before save", (ctx, next) => {
if (ctx.instance) {
ctx.instance.delivery_date = new Date(
Date.UTC(
ctx.instance.delivery_date.getFullYear(),
ctx.instance.delivery_date.getMonth(),
ctx.instance.delivery_date.getDate(),
ctx.instance.delivery_date.getHours(),
ctx.instance.delivery_date.getMinutes(),
ctx.instance.delivery_date.getSeconds()
)
);
}
next();
});
new Date().toLocaleTimeString()
andnew Date().toLocaleDateString()
? – Gulch