使用区域设置格式显示日期和时间

时间:2009-11-18 01:17:04

标签: .net vb.net

我希望这可行:

Public Shared Function ToShortDateTimeString(ByVal dateIn As Date) As String
    Return dateIn.ToShortDateString & " " & dateIn.ToShortTimeString
End Function

日期根据本地设置进行格式化,但不是时间。

我看过API示例,但是,dangit,这应该很容易并且内置到框架中。

为什么它适用于日期而不是时间?

例如,查看我的区域设置以显示时间:

http://www.screencast.com/users/Dokmanc/folders/Jing/media/cbc07eeb-1f9c-4b27-b535-91b8acbffd8e

但是,上面的函数返回: “11/17/2009 8:29:32 PM”

5 个答案:

答案 0 :(得分:3)

您可以使用DateTimeFormatInfo强制使用所需的日期/时间格式:

DateTimeFormatInfo info = new DateTimeFormatInfo();
info.ShortTimePattern = "HH:mm";

DateTime.Now.ToString(info.ShortTimePattern);

编辑:请检查上一个问题:Why doesn’t DateTime.ToShortTimeString() respect the Short Time format in “Regional and Language Settings”?

答案 1 :(得分:1)

Public Shared Function ToShortDateTimeString(ByVal dateIn As Date) As String

       // g = short date and short time
       Return dateIn.ToString("g", System.Globalization.DateTimeFormatInfo.CurrentInfo);

End Function

答案 2 :(得分:0)

听起来像是.NET问题。

解决方法可能是:

dateIn.ToString("T", CultureInfo.CurrentUICulture.DateTimeFormat)

答案 3 :(得分:0)

以dmitriy所说的为基础:

要指定格式,请参阅 http://msdn.microsoft.com/en-us/library/az4se3k1(VS.96).aspx

这应该说明不同的格式:

  Dim myDateTime As New DateTime(2001, 5, 16, 3, 2, 15)
  Console.WriteLine(myDateTime.ToString("d", CultureInfo.CurrentUICulture.DateTimeFormat))
  Console.WriteLine(myDateTime.ToString("t", CultureInfo.CurrentUICulture.DateTimeFormat))
  Console.WriteLine(myDateTime.ToString("d", CultureInfo.CreateSpecificCulture("ro-RO")))
  Console.WriteLine(myDateTime.ToString("t", CultureInfo.CreateSpecificCulture("ro-RO")))
  Console.WriteLine(myDateTime.ToString("t", CultureInfo.CurrentUICulture.DateTimeFormat))
  Console.WriteLine(myDateTime.ToShortDateString())
  Console.WriteLine(myDateTime.ToShortTimeString())

在您的特定情况下,我认为您需要的是:

返回dateIn.ToString(“d”,CultureInfo.CurrentUICulture.DateTimeFormat)& “”& dateIn.ToString(“t”,CultureInfo.CurrentUICulture.DateTimeFormat)

答案 4 :(得分:0)

试试这个:

Option Strict On
Option Explicit On

Imports Microsoft.VisualBasic
Imports System.Globalization

<System.Runtime.CompilerServices.Extension()> _
Module DateTimeExtensions

    <System.Runtime.CompilerServices.Extension()> _
    Public Function ToShortTimeStringNoSeconds(ByVal ShortTimeIn As DateTime) As String

        Dim DateTimeFormat As DateTimeFormatInfo = CultureInfo.CurrentCulture.DateTimeFormat
        Dim ShortTimePattern As String = DateTimeFormat.LongTimePattern.Replace(":ss", String.Empty)

        Return ShortTimeIn.ToString(ShortTimePattern)

    End Function 'GetShortTimeString

End Module

Dim  RegionallyFormattedTime As String = Now.ToShortTimeStringNoSeconds