首页 > 解决方案 > 在epplus中转换日期时间格式

问题描述

我想使用 epplus 将 excel 中的一列读入数据表,但每当我这样做时,我都会以 24 小时格式获得时间。我希望时间是 12 小时格式,因为它在 excel 中。

我尝试将 excel 的日期格式更改为“dd/mm/yyyy hh:mm:ss tt”,它给了我 AM/PM,但它以 24 小时格式显示时间。

worksheet.Cells["" + firstRowCell.Address + ":" + 
Regex.Replace(firstRowCell.Address, "[0-9]", "") + "" + 
worksheet.Dimension.Rows].Style.Numberformat.Format =  "dd/mm/yyyy hh:mm:ss tt";

标签: c#epplus

解决方案


听起来您正在读取格式化的显示值,而不是基础单元格值。也许这会对您有所帮助我不确定 Excel 是否将日期和时间保存为从 1900-01-01 开始的天数的两倍,小数部分是它确定一天中小时数的方式。这个数字也可以是负数或正数,所以我过去为获得正确值所做的是读取单元格值并将其转换为 DateTime。

//get the underlying value instead of the display value
var cellValue = worksheet.Cells["" + firstRowCell.Address + ":" + 
Regex.Replace(firstRowCell.Address, "[0-9]", "") + "" + 
worksheet.Dimension.Rows].Value;

var stringValue = $"{cellValue}";

//Now convert the double to a valid DateTime;
DateTime value;
var date = new DateTime(1899, 12, 30);
double doubleValue;

if (double.TryParse(stringValue, out doubleValue) &&
   (doubleValue <= 2958465) &&
   (doubleValue >= -693593))
      value = date.AddDays(doubleValue);

获得有效的 DateTime 值后,您可以使用 ToString 获得正确的 12 小时格式

value.ToString("dd/mm/yyyy hh:mm:ss tt")

推荐阅读