使用sqlite3进行日期计算

发布于 2024-08-24 18:07:23 字数 472 浏览 2 评论 0原文

我正在尝试计算日期之间的时间跨度。如果日期使用本机 sqlite3 格式“YYYY-dd-mm”进行格式化,我对此没有问题

如果日期格式不同,例如“dd-mm-YYYY”,我会如何执行此操作

我尝试了以下方法没有成功。

--选择两天之间的日期;如果日期时间字符串的格式为 YYYY-dd-mm,则此方法有效

SELECT julianday(date1) - julianday(date2) AS Span from myTable;

- 我尝试对 dd-mm-YYYY 格式的日期执行此操作,但它似乎不起作用 -- 好像无法指定日期格式。

SELECT julianday(strftime('%d-%m-%Y', date1)) - julianday(strftime('%d-%m-%Y', date2)) AS Span from myTable;

I'm trying to calculate TimeSpans between dates. I have no problem with this if the date is formatted using the native sqlite3 format 'YYYY-dd-mm'

How would I do this if the date is formatted differently, such as 'dd-mm-YYYY'

I've tried the following with no success.

--Select days between two days; this works if the datetime string is formated YYYY-dd-mm

SELECT julianday(date1) - julianday(date2) AS Span from myTable;

--I tried this for dates in the format of dd-mm-YYYY but it doens't seem to work
--It seems to be that a date format cannot be specified.

SELECT julianday(strftime('%d-%m-%Y', date1)) - julianday(strftime('%d-%m-%Y', date2)) AS Span from myTable;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小霸王臭丫头 2024-08-31 18:07:23

由于您使用的是 System.Data.SQLite,我建议使用自定义函数。这将更易于使用并与 MS SQL Server 保持一致,使其他 .NET 开发人员更容易理解和维护。

/// <summary>
/// MS SQL 2005 Compatible DateDiff() function.
/// </summary>
/// <remarks>
/// ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.SQL.v2005.en/tsqlref9/html/eba979f2-1a8d-4cce-9d75-b74f9b519b37.htm
/// 
/// 
/// </remarks>
[SQLiteFunction(Name = "DateDiff", Arguments = 3, FuncType = FunctionType.Scalar)]
public class DateDiff : SQLiteFunction
{
    public override object Invoke(object[] args)
    {
        if (args[0] == DBNull.Value || 
            args[1] == DBNull.Value ||
            args[2] == DBNull.Value)
        {
            return null;
        }
        string part = Convert.ToString(args[0]);
        DateTime startTime = ToDateTime(args[1]);
        DateTime endTime = ToDateTime(args[2]);

        switch(part)
        {
            case "year":
            case "yy":
            case "yyyy":
                return endTime.Year - startTime.Year;

            case "quarter":
            case "qq":
            case "q":
                return (endTime.Year - startTime.Year) * 4 + ((endTime.Month - 1) / 3) - ((startTime.Month - 1) / 3);

            case "month":
            case "mm":
            case "m":
                return (endTime.Year - startTime.Year) * 12 + endTime.Month - startTime.Month;

            case "dayofyear":
            case "dy":
            case "y":
            case "day":
            case "dd":
            case "d":
                return (endTime - startTime).TotalDays;

            case "week":
            case "wk":
            case "ww":
                return (endTime - startTime).TotalDays / 7.0;

            case "Hour":
            case "hh":
            case "h":
                return (endTime - startTime).TotalHours;

            case "minute":
            case "mi":
            case "n":
                return (endTime - startTime).TotalMinutes;

            case "second":
            case "ss":
            case "s":
                return (endTime - startTime).TotalSeconds;

            case "millisecond":
            case "ms":
                return (endTime - startTime).TotalMilliseconds;

            default:
                throw new ArgumentException(String.Format("Date part '{0}' is not recognized.", part));
        }

    }

    private static DateTime ToDateTime(object source)
    {
        try
        {
            return Convert.ToDateTime(source);              
        } 
        catch (Exception ex)
        {
            throw new ArgumentException(String.Format("DateDiff Input value '{0}' can not be converted to a DateTime.", source), ex);
        }
    }
}

Since you're using System.Data.SQLite I would recommend using a custom function. This will be easier to use and be consistent with MS SQL Server, making it clearer for other .NET developers to understand and maintain.

/// <summary>
/// MS SQL 2005 Compatible DateDiff() function.
/// </summary>
/// <remarks>
/// ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.SQL.v2005.en/tsqlref9/html/eba979f2-1a8d-4cce-9d75-b74f9b519b37.htm
/// 
/// 
/// </remarks>
[SQLiteFunction(Name = "DateDiff", Arguments = 3, FuncType = FunctionType.Scalar)]
public class DateDiff : SQLiteFunction
{
    public override object Invoke(object[] args)
    {
        if (args[0] == DBNull.Value || 
            args[1] == DBNull.Value ||
            args[2] == DBNull.Value)
        {
            return null;
        }
        string part = Convert.ToString(args[0]);
        DateTime startTime = ToDateTime(args[1]);
        DateTime endTime = ToDateTime(args[2]);

        switch(part)
        {
            case "year":
            case "yy":
            case "yyyy":
                return endTime.Year - startTime.Year;

            case "quarter":
            case "qq":
            case "q":
                return (endTime.Year - startTime.Year) * 4 + ((endTime.Month - 1) / 3) - ((startTime.Month - 1) / 3);

            case "month":
            case "mm":
            case "m":
                return (endTime.Year - startTime.Year) * 12 + endTime.Month - startTime.Month;

            case "dayofyear":
            case "dy":
            case "y":
            case "day":
            case "dd":
            case "d":
                return (endTime - startTime).TotalDays;

            case "week":
            case "wk":
            case "ww":
                return (endTime - startTime).TotalDays / 7.0;

            case "Hour":
            case "hh":
            case "h":
                return (endTime - startTime).TotalHours;

            case "minute":
            case "mi":
            case "n":
                return (endTime - startTime).TotalMinutes;

            case "second":
            case "ss":
            case "s":
                return (endTime - startTime).TotalSeconds;

            case "millisecond":
            case "ms":
                return (endTime - startTime).TotalMilliseconds;

            default:
                throw new ArgumentException(String.Format("Date part '{0}' is not recognized.", part));
        }

    }

    private static DateTime ToDateTime(object source)
    {
        try
        {
            return Convert.ToDateTime(source);              
        } 
        catch (Exception ex)
        {
            throw new ArgumentException(String.Format("DateDiff Input value '{0}' can not be converted to a DateTime.", source), ex);
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文