Saving date in sails js model - date

I am using moment as a third part library.
Every time a record is created in the model the date is stored with 0:00 time. Such as Thu Dec 03 2015 00:00:00 GMT+0200 (EET) .
var dateToday = moment(moment().format("YYYY-MM-DD HH:mm")).toISOString();
This is the date I am putting in the date field.
I've also tried with toDate() and new Date()... the same.
When I try to print it, the time is OK, but when I put it in a record it is always stored as 0:00.

What is your Database adapter? You DB field could be set to a simple date format?
Otherwise you should update your question with you DB Adapter and your Model definition (and if using SQL database, your scheme for that field)
You should be using datetime as your attribute values.

const moment = require('moment');
Here is a working example on how to save date (now) into MYSQL DB through ORM of Sails.js:
moment().format('YYYY-MM-DD HH:mm:ss')}
With the ORM class:
await TagsToScrape.update({
id: hashTag.id
}).set({lastProcessStarted: moment().format('YYYY-MM-DD HH:mm:ss')});
P.S. You can always check whether time is valid like this:
moment().format('YYYY-MM-DD HH:mm:ss')}.isValid() // true

Related

best way insert time with zone JavaScript postgres 9.6

What is the best way to insert the now() date time in postgresql using JavaScript? I've followed some answers but nothing clear, I'd like to find pure JavaScript method, and not with moment.js
It would be so much better if you inserted the table's create SQL code, probably part of your application's code in javascript and more information about the situation you're in to your question, in order for people who want to help, to better understand it.
Assuming you have a table with a createdAt column which its type is TIMESTAMP and you want to fill the query below with proper value for :nowValue which is current date and time, and you don't want to use Postgres's built in functionalities (like CURRENT_TIMESTAMP) or any other javascript library (like moment):
INSERT INTO "myTable" ("createdAt") VALUES (:nowValue)
First you have to init a new Date object:
const nowValue = new Date();
Then you can convert the newly created object to string and use it in your query using different methods which return different values:
nowValue.toDateString(); // "Fri Jan 12 2018"
nowValue.toGMTString(); // "Fri, 12 Jan 2018 11:09:43 GMT"
nowValue.toISOString(); // "2018-01-12T11:09:43.153Z"
nowValue.toLocaleDateString(); // "1/12/2018"
nowValue.toLocaleString(); // "1/12/2018, 2:39:43 PM"
nowValue.toUTCString(); // "Fri, 12 Jan 2018 11:09:43 GMT"
Some of the above methods only outputs the date and not the time, which will make column's time value to be set to 00:00:00.000000.
For more detailed information about these methods and how they are different see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

How to convert date format in mongodb

I am using an API (so I have no control over the fields) - one of the fields is of type Date.
Now, I find that the date stored in the records resembles the following value:
{
...
"foobarDate": "2013-05-26T05:00:00.000Z",
...
}
Now I wish to retrieve some records based on this date - for example, I need to retrieve all the records whose fooBarDate is earlier than today's date.
If I use Javascript's Date() functionality, then I get the date in the following format:
Wed Jun 19 2013 21:13:50 GMT+0530 (IST)
If I try to design my query as follows...
{
"fooBarDate": {
"$lte": <the date calculated in javascript>
}
}
...I do not get the records - I get an empty array - I suspect it is due the reason that the format of the Date stored in MongoDB is different from the one I am passing.
How to convert the Javascript date format to the mongodb format? Or at least, how do I get the current date in the format stored in MongoDB?
P.S. I am using nodeJs and wish to query the DB in this case.
Mongo stores dates as ISODate objects. Just wrap our date into ISODate constructor:
{
"fooBarDate": {
"$lte": ISODate("2013-05-26T05:00:00.000Z")
}
}
The correct data format if you pass a string into the query is ISO8601 which is looks like you have done, however you can also pass the javascript date object into the query directly and get the same result. It looks like you may be missing the proper brackets which could be causing your query to fail. Try reformatting your code in this manner (edit I am using mongoose, but I think straight mongo is the same):
var currentTime = new Date;
orm.Records.find({lastUpdate:{$lte:currentTime}})

Using $where to query dates in MongoDB behaving differently in different environments

I'm using $where to query objects by month and date using code like the following to get UserInfo collections with a Birthdate of May 7:
db.UserInfo.find( function() {
var d = new Date(this.Birthdate);
return d.getDate() === 7 && d.getMonth() === 4;
});
This works perfectly locally, returning UserInfo objects with birthdates set to May 7th. However, this breaks remotely (Heroku+Mongolab) because I get back objects with Birthdate set to 1210222800000 for example, which is May 8th. Why is this happening and how can I get mongo to return the correct objects?
It looks like a time zone issue. I assume your dates are all supposed to be "midnight" on the day in question. This one is 8 hours off.
# TZ=UTC date -d #1210222800000
Tue Jun 8 08:00:00 UTC 40320
Since JSON doesn't really have a Date type, you have to be really clear where the conversion happens. Best practice is that it's the app's responsibility to always convert to UTC before sending to the database. (And to strip off the time if you're trying to just store a date. Otherwise your date comparisons will be wrong.)
It's also best practice to run your database servers and application servers in the UTC time zone. (The app should convert to local time if desired. Usually per-user since users are often in different time zones.)

How to convert from string to date data type?

I am uploading data from a csv file to MongoDB. It is taking OrderDate as string data type due to which facing problems while creating reports using a BI tool.
I have about 10000 records in my collection.
Could anyone help me how can I change the data Type of OrderDate to Date with a single query?
I don't think that you can change field's type with single query. The easiest way is to convert data strings into Date format using ISODate function during the insertion. But, if you want to process the data you already inserted, you can do it with the following code using mongodb console:
db.collection.find().forEach(function(element){
element.OrderDate = ISODate(element.OrderDate);
db.collection.save(element);
})
This code will process each element in your collection collection and change the type of Orderdate field from String to Date.
db.messages.find().forEach(function(doc) {
doc.headers.datestamp = new Date(Date.parse(doc.headers.Date.toString()));
db.messages.save(doc);
})
This worked well to convert this sort of text:
Tue, 14 Nov 2007 03:22:00 -0800 (PST)
The text is from an email archive known as the Enron Corpus.

How to save date properly?

I'm trying to save date (using C# official driver):
val = DateTime.Parse(value).Date; //Here date is {11/11/2011 12:00:00 AM}
var update = Update.Set("Date", val);
...
When I select Date from the database, the value is {11/10/2011 10:00:00 PM}
How to save only the date I want?
c# driver by default (without extra settings) saving local dates as utc date into database (date - time zone offset) but reading back without any action (so, utc date).
Because of this when you loading datetime from database you receive diff in 2 hours (your timezone offset). There are two approaches how to say to mongodb c# driver convert utc dates to local timezone dates during deserialization:
1.through the attributes for particular date field:
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime SomeDateProperty {get;set;}
2.through global settings for all datetime fields (default is UtcInstance):
DateTimeSerializationOptions.Defaults = DateTimeSerializationOptions.LocalInstance;
Once you will do #1 or #2 you will see local date.
Update:
#2 is obsolete in latest driver version so use code below instead:
BsonSerializer.RegisterSerializer(typeof(DateTime),
new DateTimeSerializer(DateTimeSerializationOptions.LocalInstance));
Update:
#2 has changed again:
BsonSerializer.RegisterSerializer(typeof(DateTime), DateTimeSerializer.LocalInstance);
You're running into a timezone issue. Your date object is probably in a timezone other than UTC (2 hours ahead by the looks of it) or your default timezone is set to something other than UTC. The driver will convert the date to the appropriate timezone before storing it in the database.
Normally you wouldn't notice this since the reverse (retrieving the UTC date from the database) should convert it back to the original timezone. There might be an issue with the driver you're using or C# might require a bit more code to get it right.
Storing dates as strings is usually not a good idea since it disables range queries on dates.
Mongo stores everything in UTC, in case your date time is UTC this will help
val = DateTime.SpecifyKind(val , DateTimeKind.Utc);
var update = Update.Set("Date", val);
2.2.4.26 has changed again:
BsonSerializer.RegisterSerializer(typeof(DateTime), DateTimeSerializer.LocalInstance);
In my case [BsonDateTimeOptions(Kind = DateTimeKind.Local)] doesn't worked.
What i did is below
DateTime _someDateProperty ;
public DateTime SomeDateProperty
{
get { return _someDateProperty ; }
set
{
_someDateProperty = new DateTime(value.Ticks, DateTimeKind.Local);
}
}
Mongodb Date value stored in "UTC DateTime" format which comprises of both date & time. so you just cannot store date alone in the field. Instead you can get the date part alone in your application code after retrieving from mongo.
like in c#
datevalue.ToString("MM/dd/yyyy");
or
datevalue.ToShortDateString()