How to save mongoose date-time in particular time-zone - node.js

Mongoose is saving date-time as ISODate("2017-04-25T09:40:48.193Z")in UTC format. How can i change its time zone to my local server timezone. So i need not to change the time every time i retrieve it from db. Here is my model schema:
var MyModelSchema = new mongoose.Schema(
{
id: Number,
description: String,
created: {type: Date},
modified: {type: Date, default: Date.now},
},
{
collection: 'my'
}
);
PS: I am aware that it is preferred to save time in UTC format but here my requirement is to save it in specified time-zone.

you can save users timezone and while updating add the time zone value to this new object. Better to use moment.js to convert this.
moment

Even thought it is not a good practice to store time in local format but this might help -
date = new Date(); //2017-04-25T06:23:36.510Z
date.toLocaleTimeString(); //'11:53:36 AM'
localDate = ""+d; //'Tue Apr 25 2017 11:53:36 GMT+0530 (IST)'
changes will be done where you are saving the Object -
var date = new Date(); //2017-04-25T06:23:36.510Z
date.toLocaleTimeString(); //'11:53:36 AM'
var localDate = ""+d; //'Tue Apr 25 2017 11:53:36 GMT+0530 (IST)'
var newModel = new ModelSchema()
newModel.description = 'Something';
newModel.created = locaDate;
newModel.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});

I think I have a solution. Try this one for Asia/Calcutta this can be stored as Date type in Mongoose
function getCurrentIndianDateTime(){
var moment = require('moment-timezone');
var time = moment.tz('Asia/Calcutta').format("YYYY-MM-DDTHH:MM:ss");
return new Date(time);
}

Related

how to get findOne current date value in mongodb

var todayOrderCount = await OrderDetails.find({ "createdAt": {$gte: Date()},status: 2}).count();
i need data according date choosing count
var todayOrderCount = await OrderDetails.find({"createdAt": { $gte: new Date() }, status: 2 }).count();
You should use new keyword before Date() in order to get date with date type, when you use it without new keyword it will return date as a string.
also check createdAt type in your db maybe its timestamp in that case use
new Date().getTime()

Mongoose MongoDB in Node.js - Saving datetime in local timezone

I am using Mongoose in NodeJS project. I have this schema:
let InventorySchema = new Schema({
name: String,
tradable: {
type: Date,
default: () => {
return new Date().getTime()
}
}
}, {
versionKey: false
});
I live in Prague (GMT+01:00). When I insert "line" into my document, tradable is set automatically (because of default) to datetime without GMT. For example time now is in my city 16:51 but into database its saved as 15:51
How to save correct datetime? NodeJS Date giving me correct datetime when it is called normally.
EDIT: Using Date.now not helping! Same output
Use getTimezoneOffset() It will provide you the offset :
var date = new Date(); //ex 2019-01-18T16:26:44.982Z
var offset = - date.getTimezoneOffset() / 60; //in your case 1
And you add the offset to your date.

Strange date behaviour with MongoDB

I'm writing a React Application that uses MongoDB as its database. There seems to be some strange behaviour when saving and retrieving dates from the database, specifically when updating the date in a particular document.
When I create a new document, everything is fine. However, if I try to edit the date on that document using an ajax call, the date stored in MongoDB is one day earlier than the one I selected and what is displayed in the browser. Code below to explain a little more.
The date is selected using an HTML5 <input type='date' /> element. Here's some of the code. I've included console logs at various points to show the output. Let's assume I'm selecting '30 October 2016' as the date. The date and the year get split up for display purposes elsewhere, but then joined together in the form of a JS Date object before sending to the server (see code below)
React component method:
saveChanges(e, cancel){
e.preventDefault();
const cancelled = cancel ? true : false
console.log(this.state.date); // 30 Oct
console.log(this.state.year); // 2016
const saveData = {
id: this.props.data.id,
venue: this.state.venue,
unitNumber: this.state.unitNumber,
unitName: this.state.unitName,
date: this.state.date,
year: this.state.year,
day: this.state.day,
tutorID: this.state.tutorID,
cancelled: cancelled
}
editWorkshop(saveData, (data) => {
this.props.getWorkshopDetails();
this.props.workshopDetailsSaved(data);
});
}
The above method sends the data to editWorkshop.js, an external ajax call, using axios:
import axios from 'axios';
export default function editWorkshop(input, callback){
const date = new Date(input.date + ' ' + input.year) // Rejoin date and year and convert to Date object
console.log(date); // Sun Oct 30 2016 00:00:00 GMT+0100 (BST)
const data = {
id: input.id,
venue: input.venue,
unitNumber: input.unitNumber,
unitName: input.unitName,
date: date,
day: input.day,
tutorID: input.tutorID,
cancelled: input.cancelled
}
axios.post('/editWorkshop', data).then(function(res){
callback(res.data);
})
}
And finally the express route which handles the ajax call
const express = require('express');
const Workshop = require('../data/models/Workshop');
module.exports = function(req, res){
const data = req.body
console.log(data.date); // 2016-10-29T23:00:00.000Z - here is where it seems to go wrong - notice that the date has changed to 2016-10-29 instead of 10-30. This now gets written to the database
Workshop.update({ _id: data.id }, {
$set: {
unitNumber: data.unitNumber,
date: data.date,
venue: data.venue,
tutor: data.tutorID,
session: data.day,
cancelled: data.cancelled
}
}, function(err){
if (err) {
res.send(err);
return
}
var message = 'Workshop updated'
res.send({
success: true,
message: message
});
})
}
What's really strange is that when I retrieve the data from the database elsewhere in the application, it shows the correct date in the browser - 30 Oct 2016.
Arguably this isn't a problem as the correct date is being displayed, but I'm not comfortable with this as these dates are a fundamental part of the app and I'm concerned that there could be scope for a bug in the future.
Can anyone shed any light on this?
2016-10-29T23:00:00.000Z is same as Sun Oct 30 2016 00:00:00 GMT+0100 (BST).
2016-10-29T23:00:00.000Z is in UTC(GMT) timezone. If you convert that to BST you will get the same value.
MongoDB saves the date values as UTC milliseconds since the Epoch.
From the docs:
MongoDB stores times in UTC by default, and will convert any local
time representations into this form. Applications that must operate or
report on some unmodified local time value may store the time zone
alongside the UTC timestamp, and compute the original local time in
their application logic.

Mongoose date comparison

My application will allow user to create coupons.
Coupon will be valid in datefrom and dateto period.
The thing is that every coupon should be valid for selected days, not hours.
For example since Monday(2016-06-12) to Tuesday(2016-06-13), so two days.
How should I store dates on server side and then compare it using $gte clause in Mongoose?
Thank you :-)
{ "_id" : 1, "couponStartDate" : ISODate("2016-06-26T18:57:30.012Z") }
{ "_id" : 2, "couponStartDate" : ISODate("2016-06-26T18:57:35.012Z") }
var startDate = new Date(); // I am assuming this is gonna be provided
var validDate = startDate;
var parametricDayCount = 2;
validDate.setDate(validDate.getDate()+parametricDayCount);
CouponModel.find({couponStartDate: {$gte: startDate, $lte: validDate}}, function (err, docs) { ... });
You can store expiration time as UNIX timestamp. In your Mongoose model you can use expiration : { type: Number, required: true}
If you have user interface for creating coupons then you can configure your date picker to send time in UNIX timestamp.
Or If you are getting Date string then you can use var timestamp = new Date('Your_Date_String');
And for calculation of Days you can use Moment JS. Using this you can calculate start of the date using .startOf(); and end of date using .endOf();
Timestamp return from Moment JS can be used for Mongoose query like $gte : some_timestamp and $lte : some_timestamp
If you want to validate the coupon before it is persisted, you can create a max / min value for the date field:
See this sample from official mongoose documentation on DATE validation:
var s = new Schema({ dateto: { type: Date, max: Date('2014-01-01') })
var M = db.model('M', s)
var m = new M({ dateto: Date('2014-12-08') })
m.save(function (err) {
console.error(err) // validator error
m.dateto = Date('2013-12-31');
m.save() // success
})
Hint: use snake_case or camelCase for field names

Issues when trying to format DATE from mongodb

I am trying to format a date type property on a model before displaying it. This is the code that I am using:
// MODEL
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ArticleSchema = new Schema({
title: String,
content: String,
author: { type: String, default: 'Vlad'},
postDate: { type: Date, default: Date.now }
});
ArticleSchema.methods.formatTitle = function() {
var link = this.title.replace(/\s/g, '-');
return '/article/' + link;
};
ArticleSchema.methods.snapshot = function() {
var snapshot = this.content.substring(0, 500);
return snapshot;
};
ArticleSchema.methods.dateString = function() {
var date = new Date(this.postDate);
return date.toDateString();
};
module.exports = mongoose.model('Article', ArticleSchema);
And on the client side I try to display the formatted date using:
{{ article.dateString }}
Still, whenever I load a view that contains this element, I get a 500 error:
Cannot call method 'toDateString' of undefined
EDIT1: I have no issue embedding {{ article.snapshot }} in my Views, but when it comes to the Date object, I get an error
EDIT2: When logging the dateString method using console.log(article.dateString()) I get the following:
Wed Sep 18 2013
EDIT3: This is when I get when using the code provided by dankohn. Is it just me, or is it simply running the method two times in a row?
this.postdate: Wed Sep 18 2013 23:27:02 GMT+0300 (EEST)
parsed: 1379536022000
date: Wed Sep 18 2013 23:27:02 GMT+0300 (EEST)
toString: Wed Sep 18 2013
Wed Sep 18 2013
this.postdate: undefined
parsed: NaN
date: Invalid Date
toString: Invalid Date
I've rewritten this to make perfectly clear where your date stuff is failing:
ArticleSchema.methods.dateString =
console.log('this.PostDate: ' + this.postDate)
var parsed = Date.parse(this.postDate)
console.log('parsed: ' + parsed)
var date = new Date(parsed);
console.log('date: ' + date)
var toString = date.toDateString();
comsole.log('toString: ' + toString)
return toString;
};
Separately, if this doesn't work for you, I recommend the library moment, which is much easier to work with than native Javascript dates.

Resources