Как управлять датами и временем

Как хранить даты и время в Excel

Даты и время хранятся в ячейках в виде чисел. Таким образом, значения ячеек, которые содержат даты и времена, имеют числовой тип. Число, которое указывает дату и время, состоит из компонентов даты (целая часть) и времени (дробная часть). Свойство Cell.DoubleValue возвращает это число.

Как отображать даты и время в Aspose.Cells

Чтобы отображать число как дату и время, примените нужный формат даты и времени к ячейке через свойства Style.getNumber() или Style.Custom . Свойство CellValue.DateTimeValue возвращает объект DateTime, который указывает дату и время, представляемые числом, содержащимся в ячейке.


Как переключить две системы дат в Aspose.Cells

MS-Excel хранит даты как числа, которые называются серийными значениями. Серийное значение - это целое число, которое представляет собой количество прошедших дней с первого дня в системе дат. Excel поддерживает следующие системы дат для серийных значений:

  1. Система дат 1900 года. Первая дата - 1 января 1900 года, а ее серийное значение - 1. Последняя дата - 31 декабря 9999 года, ее серийное значение - 2 958 465. Эта система дат используется в книге по умолчанию.
  2. Система дат 1904 года. Первая дата — 1 января 1904 года, её серийное значение равно 0. Последняя дата — 31 декабря 9999 года, её серийное значение равно 2 957 003. Для использования этой системы дат в рабочей книге установите свойство WorkbookSettings.getDate1904() в значение true.

Этот пример показывает, что серийные значения, хранящиеся на одной дате в разных системах дат, различны.

const AsposeCells = require("aspose.cells.node");
const path = require("path");
// The path to the documents directory.
const dataDir = path.join(__dirname, "data");
// Instantiating an Workbook object
let workbook = new AsposeCells.Workbook();
workbook.getSettings().setDate1904(false);
// Obtaining the reference of the newly added worksheet
let ws = workbook.getWorksheets().get(0);
let cells = ws.getCells();
let dateData = new Date(2023, 10, 23); // JavaScript months are 0-based
// Setting the DateTime value to the cells
let a1 = cells.get("A1");
a1.putValue(dateData);
// Check if the cell contains a numeric value
if (a1.getType() === AsposeCells.CellValueType.IsNumeric) {
console.log("A1 is Numeric Value: " + a1.getDoubleValue());
}
workbook.getSettings().setDate1904(true);
console.log("use The 1904 date system====================");
// Setting the DateTime value to the cells
let a2 = cells.get("A2");
a2.setValue(dateData);
// Check if the cell contains a numeric value
if (a2.getType() === AsposeCells.CellValueType.IsNumeric) {
console.log("A2 is Numeric Value: " + a2.getDoubleValue());
}

Результат вывода:

A1 is Numeric Value: 45253  
use The 1904 date system====================  
A2 is Numeric Value: 43791  

Как установить значение DateTime в Aspose.Cells

Этот пример устанавливает значение DateTime в ячейке A1 и A2, устанавливает пользовательский формат для ячейки A1 и числовой формат для ячейки A2, а затем выводит типы значений.

const AsposeCells = require("aspose.cells.node");
const path = require("path");
// The path to the documents directory.
const dataDir = path.join(__dirname, "data");
// Instantiating a Workbook object
let workbook = new AsposeCells.Workbook();
// Obtaining the reference of the newly added worksheet
let ws = workbook.getWorksheets().get(0);
let cells = ws.getCells();
// Setting the DateTime value to the cells
let a1 = cells.get("A1");
a1.putValue(new Date());
// Check if the cell contains a numeric value
if (a1.getType() === AsposeCells.CellValueType.IsNumeric) {
console.log("A1 is Numeric Value: " + a1.isNumericValue());
}
let a1Style = a1.getStyle();
// Set custom Datetime style
a1Style.setCustom("mm-dd-yy hh:mm:ss");
a1.setStyle(a1Style);
// Check if the cell contains a DateTime value
if (a1.getType() === AsposeCells.CellValueType.IsDateTime) {
console.log("Cell A1 contains a DateTime value.");
} else {
console.log("Cell A1 does not contain a DateTime value.");
}
// Setting the DateTime value to the cells
let a2 = cells.get("A2");
a2.putValue(new Date());
// Check if the cell contains a numeric value
if (a2.getType() === AsposeCells.CellValueType.IsNumeric) {
console.log("A2 is Numeric Value: " + a2.isNumericValue());
}
let a2Style = a2.getStyle();
// Set the display format of numbers and dates.
a2Style.setNumber(22);
a2.setStyle(a2Style);
// Check if the cell contains a DateTime value
if (a2.getType() === AsposeCells.CellValueType.IsDateTime) {
console.log("Cell A2 contains a DateTime value.");
} else {
console.log("Cell A2 does not contain a DateTime value.");
}

Результат вывода:

A1 is Numeric Value: True  
Cell A1 contains a DateTime value.  
A2 is Numeric Value: True  
Cell A2 contains a DateTime value.  

Как получить значение DateTime в Aspose.Cells

Этот пример устанавливает значение DateTime в ячейке A1 и A2, устанавливает пользовательский формат для ячейки A1 и числовой формат для ячейки A2, проверяет типы значений двух ячеек, а затем выводит значение DateTime и отформатированную строку.

const AsposeCells = require("aspose.cells.node");
const path = require("path");
// The path to the documents directory.
const dataDir = path.join(__dirname, "data");
// Instantiating a Workbook object
const workbook = new AsposeCells.Workbook();
// Obtaining the reference of the newly added worksheet
const ws = workbook.getWorksheets().get(0);
const cells = ws.getCells();
// Setting the DateTime value to the cells
const a1 = cells.get("A1");
a1.putValue(new Date());
// Check if the cell contains a numeric value
if (a1.getType() === AsposeCells.CellValueType.IsNumeric) {
console.log("A1 is Numeric Value: " + a1.isNumericValue);
}
let a1Style = a1.getStyle();
// Set custom Datetime style
a1Style.setCustom("mm-dd-yy hh:mm:ss");
a1.setStyle(a1Style);
// Check if the cell contains a DateTime value
if (a1.getType() === AsposeCells.CellValueType.IsDateTime) {
console.log("Cell A1 contains a DateTime value.");
// Get the DateTime value
const dateTimeValue = a1.getDateTimeValue();
// Now, you can use dateTimeValue as needed
console.log("A1 DateTime Value: " + dateTimeValue);
// Output date formatted string
console.log("A1 DateTime String Value: " + a1.getStringValue());
} else {
console.log("Cell A1 does not contain a DateTime value.");
}
// Setting the DateTime value to the cells
const a2 = cells.get("A2");
a2.putValue(new Date());
// Check if the cell contains a numeric value
if (a2.getType() === AsposeCells.CellValueType.IsNumeric) {
console.log("A2 is Numeric Value: " + a2.isNumericValue);
}
let a2Style = a2.getStyle();
// Set the display format of numbers and dates.
a2Style.setNumber(22);
a2.setStyle(a2Style);
// Check if the cell contains a DateTime value
if (a2.getType() === AsposeCells.CellValueType.IsDateTime) {
console.log("Cell A2 contains a DateTime value.");
// Get the DateTime value
const dateTimeValue = a2.getDateTimeValue();
// Now, you can use dateTimeValue as needed
console.log("A2 DateTime Value: " + dateTimeValue);
// Output date formatted string
console.log("A2 DateTime String Value: " + a2.getStringValue());
} else {
console.log("Cell A2 does not contain a DateTime value.");
}

Результат вывода:

A1 is Numeric Value: True  
Cell A1 contains a DateTime value.  
A1 DateTime Value: 11/23/2023 5:59:09 PM  
A1 DateTime String Value: 11-23-23 17:59:09  
A2 is Numeric Value: True  
Cell A2 contains a DateTime value.  
A2 DateTime Value: 11/23/2023 5:59:09 PM  
A2 DateTime String Value: 11/23/2023 17:59