node js - MSSQL node module automatically converts Date as DateTime - node.js

I'm retrieving the SQL Date value from sql database using MSSQL node module through node js application but the resultant record set returns the date as Date time value.
2020-11-21 in database is displayed as 2020-11-21T00:00:00
Should we need to handle this explicitly?

This is not "DateTime", that's how toString of a Date object looks like in Javascript:
If you want it to be printed in a certain format that shows only the "date" portion, you can use toLocaleDateString():
const d = new Date()
console.log(d.toLocaleDateString()) // '11/18/2020'
or, if you want the result to be formatted like the example above: yyyy-mm-dd you can do:
d.toISOString().slice(0, 10); // '2020-11-18'

Related

Reactjs Timezone convertion

I am connected mssql database and get some informations includes Date_Time.
Time is coming like 2021-01-30T15:08:25.357Z. I want to convert it to dd-mm-yy hh:mm:ss format.
So, it should be 30-01-2021 15:08:25.
I used this method but it is not exactly that I want.
var d1 = new Date(datey).toLocaleDateString("tr")
var newTime=d1+" "+
new Date(datey).getUTCHours()+":"+
new Date(datey).getUTCMinutes()+":"+
new Date(datey).getUTCSeconds()
// it returns 30/01/2021 15:8:25
Maybe, In there, I want to see time fomat with 0 such as 15:08. When hour 2 a.m it just 2:0 but I want to see it 02:00.
How should I do , is there any idea?
I would suggest using a date/time library such as moment.js, this will make date manipulation much easier, parsing and formatting your date is then very simple:
const input= "2021-01-30T15:08:25.357Z";
console.log("Input date:", input);
// To convert the date to local before displaying, we can use moment().format()
const formattedDateLocal = moment(input).format("DD-MM-YY HH:mm:ss");
console.log("Formatted date (Local Time):", formattedDateLocal );
// To display the UTC date, we can use moment.utc().format()
const formattedDateUTC = moment.utc(input).format("DD-MM-YY HH:mm:ss");
console.log("Formatted date (UTC):", formattedDateUTC );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

momentJS: Getting wrong timestamp from date in a different timezone

There is one time input i.e. start_time
I am trying to get timestamp in milliseconds for these inputs
let start_time = "17:05:00";
var start_date_moment = moment(start_time, "HH:mm:ss");
console.log(start_timestamp);
output is -> moment("2019-04-24T17:05:00.000")
This output remains same on server and local
But when I am trying to get unix timestamp in milliseconds in the same way
var start_timestamp = moment(start_time, "HH:mm:ss").valueOf();
On server at different timezone
console.log(start_timestamp);//1556125500000
console.log(moment(start_timestamp/1000).format('YYYY-MM-DD HH:mm:ss'); //2019-04-24 17:05:00
On local
console.log(start_timestamp);//1556105700000
console.log(moment(start_timestamp/1000).format('YYYY-MM-DD HH:mm:ss'); //2019-04-24 22:35:00
This start_timestamp value is different on local and server. But timestamp shouldn't change with timezone, it should remains same for all timezones. Please help me with this.
How to get the correct and same value at both places. I got this link some what related to this https://github.com/moment/moment/issues/2035
There is no issue with dates any particular format, issue is only with timestamp.
You need to take the offset into consideration when using moment (using timezones moment.js). Since no offset was passed in the input, the moment will be based on the time zone of the computer the code is running on, hence the different values..
Example:
var a = moment.tz("2013-11-18 11:55", "Asia/Taipei");
var b = moment.tz("2013-11-18 11:55", "America/Toronto");
a.format(); // 2013-11-18T11:55:00+08:00
b.format(); // 2013-11-18T11:55:00-05:00
a.utc().format(); // 2013-11-18T03:55Z
b.utc().format(); // 2013-11-18T16:55Z
If you change the time zone of a moment object using moment-timezone only affects the value of the local time. It does not change the moment in time being represented, and therefore does not change the underlying timestamp.
A Unix Timestamp is always based on UTC - you can see it as the same timestamp at any given location in the world.
Official Moment Docs on timezones
Edit:
If you use utcOffset you should pass an integer:
Example:
moment.utc("2015-10-01 01:24:21").utcOffset("-240").format('YYYYMMDD HHmmss ZZ')
// "20151001 012421 +0000"
moment.utc("2015-10-01 01:24:21").utcOffset(-240).format('YYYYMMDD HHmmss ZZ')
// "20150930 212421 -0400"
MomentJS allows offset-arguments to be passed as string, but it expects the string to be in one of the ISO8601 formats: [+/-]HH:mm or [+/-]HHmm.
To avoid this all together you could, if known, pass the location as an argument like
moment.tz(start_time, "HH:mm:ss", "Asia/Kolkata").valueOf();
as mentioned in the first example above..

Moment.js - formatting an existing time?

I am using moment.js to work with dates and times in node.js. So far I've been able to do everything I need with it, but I am having problems formatting a time.
Here's the scenario:
User enters data (an integer), which is logged in a database, along with date (in the format YYYY-MM-DD) and time (in the format HH:MM:SS).
Next time the user goes to enter data, the previous value is read in and compared (higher, lower or equal to) the new value. However I also want to display a message such as "The last time you submitted your data was at TIME on DATE". In this case, I'd like time to be displayed in a different format (e.g. "h:mm a" i.e. "12:34 pm").
Can I use moment to format an existing date, or can moment only return current date/time? In my code I have the following function:
function userFormattedTime(time)
{
let uTime = moment(time).format('h:mm a');
return uTime
}
However when I call this function and pass it the time (taken from the database), I get "Invalid Time". What am I doing wrong?
You would parse the string from a string back to a moment object, then you can use moment to reformat the date into any other format.
I guess what you are doing wrong is not telling moment what you're sending it back, i.e. it doesn't understand the formatted string you're supplying.
Notice the format values HH:mm:ss which vary in case. The case is important and should be set to match your requirements. https://momentjs.com/docs/#/parsing/
// Original date time string
var rawDateTime = "02-02-2018 10:20:30";
// convert string to a moment object
var originalDate = moment(rawDateTime, "MM-DD-YYYY HH:mm:ss");
// Format a new string from the moment object
var newFormattedString = originalDate.format('h:mm a');
In order to calculate the difference of moment objects you can use the diff function. https://momentjs.com/docs/#/displaying/difference/
// Two different dates
var dateOne = moment("02-02-2018 10:20:30", "MM-DD-YYYY HH:mm:ss");
var dateTwo = moment("04-04-2018 10:20:30", "MM-DD-YYYY HH:mm:ss");
// Get the difference of the two dates
var diff = dateOne.diff(dateTwo);

MongoDB date range query

I am using node.js and Mongo DB in my application.
I have stored date in a field(datetime) of an entry in a MongoDB as:
db.collection('person').insertOne({"name": "ABC","age": "40","datetime": Date()}
This outputs date as:"datetime":"Mon Nov 21 2016 00:47:39 GMT-0500 (Eastern Standard Time)"
Now I am trying to find all entries which are greater than a particular date.
For this I do the following:
db.collection('person').find( {'datetime':{$gt: startingdate})
where startingdate contains 22,11,2016.
This doesn't work and fetches me all the records that have a datetime field.
I even tried using :
startingdate = Date(22,11,2016)
and
startingdate = Date(2016,11,22)
but to no avail. Can someone help me figure this out?
Thanks!
Use new Date() instead of Date().
new Date() returns date object whereas Date() returns string representation of datetime.
You need to send date object to MongoDB so that it can transform the date object to ISODate.

Javascript momentjs convert UTC from string to Date Object

Folks,
Having a difficult time with moment.js documentation.
record.lastModified = moment.utc().format();
returns:
2014-11-11T21:29:05+00:00
Which is Great, its in UTC... When I store that in Mongo, it gets stored as a String, not a Date object type, which is what i want.
What I need it to be is:
"lastModified" : ISODate("2014-11-11T15:26:42.965-0500")
But I need it to be a native javascript object type, and store that in Mongo. Right now if i store the above, it goes in as string, not Date object type.
I have tried almost everything with moment.js. Their toDate() function works, but falls back to my local timezone, and not giving me utc.
Thanks!
Saving a Javascript Date object will result in an ISODate being stored in Mongo.
Saving an ISO date as a Javascript String will result in a String being stored in Mongo.
So, this is what you want: record.lastModified = new Date(moment().format());
Not an ideal solution, But I achieved the same result, by manually converting it to ISODate object through monogo shell. We need the ISODate for comparison/query for aggregating results, so we run this script before running our aggregate scripts.
Inserting local time string by using moment().format().
"createdDt" : "2015-01-07T17:07:43-05:00"`
Converting to an ISODate (UTC) with:
var cursor = db.collection.find({createdDt : {$exists : true}});
while (cursor.hasNext()){
var doc = cursor.next();
db.collection.update(
{_id : doc._id},
{$set: {createdDt : new ISODate(doc.createdDt)}})
}
results in
"createdDt" : ISODate("2015-01-07T22:07:43Z")"
Note the time got converted
T17:07:43-05:00 to T22:07:43Z
I could not find any solution for inserting BSON ISODate format (which is UTC by default) from JavaScript directly, while inserting a new document, it seems to be available through pyMongo & C#/Java Drivers though. Trying to look for an maintainable solution

Resources