【问题标题】:Text to Date Conversion in AccessAccess 中的文本到日期转换
【发布时间】:2012-08-23 06:55:57
【问题描述】:

我的 Access 2007 表格中有一个文本列,格式为“m/d/yyyy hh:mi:ss”,即 1-2 位数月份 1-2 位数日期 4 位数年份和“美国”日期格式。本地日期格式为 dd/mm/yyyy。

我想将这些日期转换为日期/时间字段,以便对它们进行排序,但是当我使用 CDate 运行更新查询时,它对月份和日期的处理不一致。天数 > 12 没问题,因为日期是明确的,但它会将 8 月 1 日(2011 年 8 月 1 日)转换为 1 月 8 日...

我无权更改我的语言环境 - 如果您可以暂时这样做,这可能是一种创可贴。

我可以通过对 Left、Right、Mid、InStr 等进行大量工作来“强制”转换,但由于 1-2 位数的日期和月份,这比应有的工作量要多得多。

我想要(但找不到)是 Borland Delphi/Pascal 中 StrToDate 的 VB 等效项,您可以在其中传入日期字符串和一个格式字符串,该字符串告诉转换每个数字代表什么。

在 Delphi 中,这很简单:-

MyDate:= StrToDate(MyAmericanFormattedDate,'d/m/yyyy hh24:mi:ss');

有 VB 等价物吗?

【问题讨论】:

    标签: ms-access date datetime


    【解决方案1】:

    在 VBA 中没有像 Delphi 函数那样的东西。您可以创建一个函数来正确转换字符串值。而且你不需要使用LeftRightMidInStr 函数。 Split() 函数从 Access 2000 开始可用,因此您可以拆分日期部分并将它们提供给 DateSerial() 函数。

    Public Function DateFromAmericanFormat(ByVal pIn As String, _
            Optional ByVal pDelimiter As String = "/") As Date
        Dim strDate As String
        Dim strTime As String
        Dim dteReturn As Date
        Dim astrFirstSplit() As String
        Dim astrDateParts() As String
        Dim intMonth As Integer
        Dim intDay As Integer
        Dim intYear As Integer
    
        astrFirstSplit = Split(pIn, " ")
        strDate = astrFirstSplit(0)
        strTime = astrFirstSplit(1)
    
        astrDateParts = Split(strDate, pDelimiter)
        intMonth = CInt(astrDateParts(0))
        intDay = CInt(astrDateParts(1))
        intYear = CInt(astrDateParts(2))
        dteReturn = DateSerial(intYear, intMonth, intDay) + CDate(strTime)
        DateFromAmericanFormat = dteReturn
    End Function
    

    这只是一个粗略的轮廓。它将在“下标超出范围”的 Null 输入上失败。所以这可能需要改进,但希望这是一个合理的起点。

    【讨论】:

    • 谢谢,很好的解决方案 - 更多代表(好像你需要它:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多