1

我在电子表格中有一个单元格,它是 Excel 中的一个日期对象,但是当它来自 C1 的 xls 类时,它变成了一个双精度对象(类似于 2009 年 1 月 7 日的 39820.0)。我读到这是儒略日期格式。有人可以告诉我如何将它解析回 C# 中的 DateTime 吗?

更新:看起来我可能没有儒略日期,而是自 1899 年 12 月 30 日以来的天数。

4

8 回答 8

10

我认为 Excel 只是使用标准的 OLE 自动化DATE类型,可以使用该DateTime.FromOADate方法进行转换。

这段代码,

using System;

namespace DateFromDouble
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(DateTime.FromOADate(39820.0));
        }
    }
}

输出:

1/7/2009 12:00:00 AM
于 2009-02-04T21:42:33.273 回答
8

System.Globalization 中有一个 JulianCalendar 类;以下是您将如何使用它:

            JulianCalendar c = new JulianCalendar();
            DateTime time = c.ToDateTime(2009, 1, 7, 0, 0, 0, 0);
            Console.WriteLine(time.ToShortDateString());

编辑:

如果实际上是“1900”以来的几天,那么您可以这样做:

public static DateTime DaysSince1900(int days)
{
    return new DateTime(1900, 1, 1).AddDays(days);
}



 DateTime time = DaysSince1900(39820);
 Console.WriteLine(time.ToShortDateString()); //will result in "1/9/2009"
于 2009-02-04T20:51:57.307 回答
2

该数字看起来像“自 1900 年以来的天数”值。

于 2009-02-04T20:51:10.380 回答
1

看看这篇文章:http ://dotnet-jeeves.blogspot.com/2006/02/convert-julian-date-to-systemdatetime.html

于 2009-02-04T20:50:37.277 回答
1

给你。

http://dotnetblogger.com/post/2009/02/26/Convert-DateTime-to-Julian-Date-in-C.aspx

于 2010-04-18T21:22:24.897 回答
1

在处理 Excel 日期时,日期可能是日期的字符串表示形式,也可能是 OA 日期。这是我不久前写的一个扩展方法,以帮助促进日期转换:

/// <summary>
/// Sometimes the date from Excel is a string, other times it is an OA Date:
/// Excel stores date values as a Double representing the number of days from January 1, 1900.
/// Need to use the FromOADate method which takes a Double and converts to a Date.
/// OA = OLE Automation compatible.
/// </summary>
/// <param name="date">a string to parse into a date</param>
/// <returns>a DateTime value; if the string could not be parsed, returns DateTime.MinValue</returns>
public static DateTime ParseExcelDate( this string date )
{
    DateTime dt;
    if( DateTime.TryParse( date, out dt ) )
    {
        return dt;
    }

    double oaDate;
    if( double.TryParse( date, out oaDate ) )
    {
        return DateTime.FromOADate( oaDate );
    }

    return DateTime.MinValue;
}
于 2010-04-18T21:34:04.187 回答
1

有两种方法可以进行此转换 -

  1. OLE 自动化日期方法 --

    double doubleDate = 43153.0;
    DateTime normalDate = DateTime.FromOADate(doubleDate);
    /* {2/22/2018 12:00:00 AM} */
    
  2. DateAdd() 方法,使用该方法,可以指定要转换为的日期类型

    double doubleDate = 43153.0;
    DateTime normalDate = new DateTime(1899, 12, 30, 0, 0, 0, DateTimeKind.Utc).AddDays(doubleDate);
    /* {2/22/2018 12:00:00 AM} */
    

注意:这个日期常数 {12h December 31, 1899} 称为都柏林儒略日,记录在儒略日

于 2020-12-16T19:10:17.910 回答
0

只需将有问题的单元格格式化为日期,使用 CTRL+1,然后选择所需的格式。

于 2014-11-19T23:10:51.367 回答