Create timezone-aware date in javascript - javascript

When I create objects in my MongoDB using Mongoose, the dates are formatted as, for instance, 2016-10-10T15:35:52.764Z (it might be yyyy-MM-ddTHH:mm:ssZ). If I use Date.now() in JavaScript, I get a timestamp.
How can I create the same date format as Mongoose with javascript?
Edit
It seems I can use
new Date().toISOString();
but what is the difference of, for instance, Date.now() and new Date()?
Are there any reasons for not using new Date() instead of a function under the Date object (that somehow already seems to be initialized without writing new Date()?)

you can use moment.js and run like this
moment().format('YYYY-MM-DDTHH:mm:ss'); // print 2016-10-11T15:25:36

Related

How to convert JavaScript Date into PostgreSQL Time (no timezone)?

I use knex with PosgreSQL. I have a table with a Time column.
After trying to insert data in the table, knex throws an error with the following message:
...invalid input syntax for type time: \"2021-07-21T14:40:00.000+03:00\..."
Code example
await knex('table_name')
.insert({ id: 1, time: new Date() })
What is a correct way to preserve JavaScript Date object as a PosgreSQL Time? Should I use 3rd party libs? Or it can be done using knex only?
I was able to fix this issue by manually converting the JavaScript Date object into one of the supported formats of the PostgreSQL.
The 8.5.1.1. Dates and 8.5.1.2. Times chapters have a full list of supported types.
My solution was to use date-fns/format (e.g. format(new Date(), 'HH:mm') // 14:00)
P.S. I'm not sure if this approach is right but it works.

Get JavaScript local date from Moment JS

Consider the code :
let now = moment();
console.log(now.format()); // 2019-11-25T20:23:50+02:00
console.log(now.toDate()); // 2019-11-25T18:23:50.916Z
This is the output on my local machine , and when I check the app on Heroku
it gives the same values , even though I changed the TZ like this :
heroku config:add TZ="Asia/Jerusalem"
How can I get a JavaScript Date (Not a String !) object of my localtime , meaning 2019-11-25T20:23:50 ?
Let's walk through your code example:
let now = moment();
You create a Moment object. You don't pass any parameters, so it is initialized using the current timestamp (as if you called Date.now()) and set to "local mode".
console.log(now.format()); // 2019-11-25T20:23:50+02:00
By calling format, you ask the Moment object to produce a String. Since it's in local mode, the offset that applies to that moment in time for the local time zone is emitted in the result, and the wall time shown in the result is adjusted for that offset. In this case, the local time is two hours ahead of UTC. You then pass that string to console.log, which emits it to the console.
console.log(now.toDate()); // 2019-11-25T18:23:50.916Z
By calling toDate, you ask the Moment object to create a Date object. The "mode" of the moment object is no longer relevant because Date objects don't track anything other than a timestamp. Thus, the timestamp within the Moment object becomes the timestamp for the resulting Date object. Since you derived the Moment object from the current time, the result is the same as if you just called new Date() to begin with.
You then pass the string to console.log - except one can't just log an object, so it first has to convert it to something so you can see it. Here's the interesting part: There is no spec for this behavior. Implementations of ECMAScript can do whatever they like in this regard. Some implementations, like in your example, will call .toISOString() and log the result. Since .toISOString() displays the result in UTC, the result of logging a Date object is also shown in UTC. But other implementations will call .toString() on the Date object and log that, the result being in local time. It's entirely possible some future implementation could show the result in some graphical or interactive output. The point being, you can't rely on the behavior of console.log(Date) to be consistent.
No amount of changing your time zone settings will change this result. The Date object is inherently UTC-based, your output is also UTC-based, and UTC is the same over the whole planet (by design).
If you want the time zone reflected in the string output, you must use a function that produces a string with respect to local time. As you showed, you'll get that with .format() on a Moment object in local mode. You can also get one from calling .toString() on a Date object (but the resulting string is not in the same ISO 8601 format).
i would try,
moment().local().toDate()
but if you are planning to save date into db it's good practice to save time in UTC format for easier global conversion.
If you want to work timezones you may require also moment timezone package - https://momentjs.com/timezone/docs/
npm install moment-timezone
Hope this helps :)

get date from firebase format change

earlier we push date use native Firebase format
createAt:admin.firestore.Timestamp.fromDate(new Date)
so data store like this
"createAt": {
"_seconds": 1563181560,
"_nanoseconds": 567000000
}
new we change like this
createAt:new Date().toISOString()
now store like this
"createAt": "2019-07-17T07:17:05.115Z"
buts some date store like this because we use native date format
now how can i call old date to new date format? moste of the data sote like native date method is that any way to change new method?
The Firestore Timestamp type has many conversion methods. Just like it has a fromDate() it also has a toDate() method. So if you reload the data from Firestore and get a Timestamp object, you can then get a date with timestamp.toDate() and thus an ISO-8859 formatted string with timestamp.toDate().toISOString().

Date format for sitemap

I'm using gadicohen:sitemaps with Meteor to create my sitemaps and I'm not sure how to set the lastmod date field. The documents state not to use new Date(), so what date format should I use.
{ page: '/x', lastmod: new Date() },
They aren't saying not to use Date as a type, they are saying that you should not create a new Date() every time the sitemap is requested.
Instead, keep in your collection the time that the page was last modified, and use that in the sitemap

How to process data before set or get operation?

I am using primeNG calendar and I got a model called myDate and a dateformat. ngModel directive referencing to a Date property.
<p-calendar [(ngModel)]="myDate" dateFormat="dd/mm/yy"></p-calendar>
But problem is I want to store myDate value as Unix Timestamp. So I need to convert myDate to milliseconds before set and convert it to date object with dateformat before get operation. Is there any way to do this?
private myDate;
setMyDate(myNewDate){
this.myDate = convertDateToTimestamp(myNewDate)
}
getMyDate(){
return convertTimestampToDate(this.myDate)
}
You can call getTime() on this date object to get it in unix form. It comes out in milliseconds.
new Date("2013/09/05 15:34:00").getTime();
It may have decimal bits so wrapping it in Math.round would clean that.
Math.round(new Date("2013/09/05 15:34:00").getTime());
how to convert a string to a Unix timestamp in javascript?
You could use getters and setters to achieve this, which is actually very close to what you already have:
private _myDate;
set myDate(myNewDate){
this._myDate = convertDateToTimestamp(myNewDate)
}
get myDate(){
return convertTimestampToDate(this._myDate)
}

Categories

Resources