乐闻世界logo
搜索文章和话题

How to store ISO 8601 Datetime in Sequelizejs

1个答案

1

Storing ISO 8601 date and time formats in Sequelize is a common requirement, as this format ensures compatibility of dates and times across various systems. Sequelize is an asynchronous ORM framework built on Node.js, supporting databases such as PostgreSQL, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It enables users to interact with databases in an object-oriented manner.

Data Type Selection

First, to correctly store ISO 8601 date and time formats in Sequelize, ensure the corresponding field in your model uses the DATE or DATEONLY data type. The DATE type stores dates with time in the database, adhering to the ISO 8601 standard (e.g., 2023-03-30T15:19:30Z).

Model Definition

Assume we have an Event model that includes the start time of an event. We can define it as follows:

javascript
const { Model, DataTypes } = require('sequelize'); const sequelize = new Sequelize('sqlite::memory:'); class Event extends Model {} Event.init({ eventName: DataTypes.STRING, startTime: DataTypes.DATE }, { sequelize, modelName: 'event' });

In this model, the startTime field is specified as DATE, allowing storage of both date and time.

Storing ISO 8601 Date and Time

When creating or updating an event, directly set the date and time using an ISO 8601 string:

javascript
const newEvent = await Event.create({ eventName: 'International Conference', startTime: '2023-03-30T15:19:30Z' });

Sequelize automatically converts ISO 8601 strings into the database-supported date and time format. For PostgreSQL databases, this results in a timestamp type with time zone information.

Retrieving and Using Date and Time

When retrieving date and time from the database, Sequelize automatically converts it back to a JavaScript Date object, which you can directly use in your code.

javascript
const event = await Event.findByPk(1); console.log(event.startTime); // This displays a JavaScript Date object

Notes

  • Verify that time zone settings for both the database and Node.js server are correctly configured to prevent time zone conversion issues.
  • Using ISO 8601 format for date and time operations enhances cross-system compatibility and maintainability.

By following this approach, Sequelize efficiently handles ISO 8601 date and time formats, meeting data standardization requirements while supporting application internationalization and scalability.

2024年8月9日 00:01 回复

你的答案