Access中的文本到日期转换

时间:2012-08-23 06:55:58

标签: ms-access date datetime

我的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中VB等效的StrToDate,你传入日期字符串和格式字符串,告诉转换每个数字代表什么。

在Delphi中,它会像以下一样简单: -

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

是否有VB等价物?

1 个答案:

答案 0 :(得分:2)

VBA中没有像Delphi那样的功能。您可以创建一个函数来正确转换字符串值。您无需使用LeftRightMidInStr函数。自Access 2000以来,Split()功能已可用,因此您可以拆分日期部分并将其提供给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输入上失败,并且“下标超出范围”。所以这可能需要改进,但希望这是一个合理的起点。

相关问题