FormatDateTime 函数 (Visual Basic)

更新:2007 年 11 月

返回一个表示日期/时间值的字符串表达式。

Function FormatDateTime(
   ByVal Expression As DateTime,
   Optional ByVal NamedFormat As DateFormat = DateFormat.GeneralDate
) As String

参数

  • Expression
    必选。要格式化的 Date 表达式。

  • NamedFormat
    可选。指示所使用的日期/时间格式的数值。如果省略,则使用 DateFormat.GeneralDate。

设置

NamedFormat 参数具有下列设置。

常数

说明

DateFormat.GeneralDate

显示日期和/或时间。将日期部分显示为短日期。如果有时间部分,则用长时间格式显示。如果两部分都有,则两部分都显示。

DateFormat.LongDate

使用计算机的区域设置中指定的长日期格式来显示日期。

DateFormat.ShortDate

使用计算机的区域设置中指定的短日期格式来显示日期。

DateFormat.LongTime

使用计算机区域设置中指定的时间格式来显示时间。

DateFormat.ShortTime

使用 24 小时格式 (hh:mm) 显示时间。

异常

异常类型

错误号

条件

ArgumentException

5

NamedFormat 设置无效。

如果正在升级使用非结构化错误处理方式的 Visual Basic 6.0 应用程序,请参见“错误号”一列。(您可以根据 Number 属性(Err 对象) 比较错误号。) 然而,如果可能,应当考虑用 Visual Basic 的结构化异常处理概述 替换这种错误控制。

备注

Date 数据类型始终包含日期和时间信息。为进行类型转换,Visual Basic 将 1/1/1(公元 1 年 1 月 1 日)作为日期的中性值,将 00:00:00(午夜)作为时间的中性值。如果您将 Date 值格式化为日期/时间字符串,FormatDateTime 将不在结果字符串中包含中性值。例如,如果将 #1/1/0001 9:30:00# 转换为字符串,结果为“9:30:00 AM”;日期信息被取消了。但是,日期信息仍然在原来的 Date 值中提供,并可以使用 DatePart 等函数恢复。

说明:

如果将 Expression 参数作为 String 文本传递,FormatDateTime 会根据应用程序的 CurrentCulture 设置解释该参数。但是,如果您将它作为 Date 文本传递,则由于 FormatDateTime 始终按照“英语(美国)”区域性来解释 Date,应该使用格式 #mm/dd/yyyy#。这是非常必要的,因为如果应用程序使用一个区域性中的 Date 来进行开发和编码,但却在具有不同区域性的平台上执行,则将无法正确地分析 Date。

示例

本示例演示 FormatDateTime 函数的用法。

' English (US) format.
Dim TestDate As DateTime = #3/12/1999#

' FormatDateTime returns "Friday, March 12, 1999".
' The time information is neutral (00:00:00) and therefore suppressed.
Dim TestString As String = FormatDateTime(TestDate, DateFormat.LongDate)

要求

命名空间:Microsoft.VisualBasic

**模块:**Strings

**程序集:**Visual Basic 运行库(在 Microsoft.VisualBasic.dll 中)

请参见

参考

FormatCurrency 函数 (Visual Basic)

FormatNumber 函数 (Visual Basic)

FormatPercent 函数 (Visual Basic)

ArgumentException

DatePart 函数 (Visual Basic)

字符串操作摘要