2012-06-12 112 views
6

所以我们可以说我有1400,我想将其转换成2:00 PM如何在24小时时间换算成12小时VB.net为hh:mm AM/PM

我试过如下:

Dim convertedTime As String = DateTime.ParseExact(theTime,"HHmm", Nothing) 

而且它会给我这样的:

2012年6月12日下午二点00分00秒

我不希望日期部分,我也不需要秒。我需要的只是2:00 PM

我怎么能做到这一点?谢谢!

+0

ParseExact不返回字符串。你有Option Strict On吗? –

回答

10

ParseExact方法返回的值为DateTime,而不是字符串。如果将其分配给字符串变量,则会自动将其转换为标准格式。

如果你想在一个特定的格式,然后格式化DateTime值的字符串:

Dim d As DateTime = DateTime.ParseExact(theTime,"HHmm", Nothing); 
Dim convertedTime As String = d.ToString("hh:mm tt") 
+0

感谢工作就像一个魅力〜 – eastboundr

0

有两种方法来实现这一目标。

选项1(使用standard date and time format strings):

Dim theTime As DateTime = new DateTime(2008, 4, 10, 6, 30, 0) 
Dim convertedTime As String = 
    theTime.ToString("t", CultureInfo.CreateSpecificCulture("en-us")) 

选项2(使用custom date and time format strings):

Dim theTime As DateTime = new DateTime(2008, 4, 10, 6, 30, 0) 
Dim convertedTime As String = theTime.ToString("hh:mm tt") 

在两种情况下convertedTime6:30 AM

+0

你不需要'en-us'文化,你可以使用'CultureInfo.InvariantCulture'。 –

+1

@TimSchmelter使用CultureInfo.InvariantCulture时,标准格式字符串“t”不会返回AM/PM。请参阅https://compilify.net/1u5 –

+0

对不起,您是对的,我忽略了选项1和2中的差异。 –

1
Dim theTime = New Date(2012, 6, 12, 14, 0, 0) 
Dim formatted = theTime.ToString("h:mm tt", Globalization.CultureInfo.InvariantCulture) 

Custom Date and Time Format Strings

+0

您缺少解析1400部分的代码。 – JDB

+0

@ Cyborgx37:这是这个问题的误导部分。实际上,OP在解析1400到DateTime时没有问题:_“...它会给我这个:6/12/2012 02:00:00 PM 我不想要日期部分,我也不需要秒。我需要的只是下午2点“_他只是想将DateTime变量转换为适当格式的字符串 –

1

Label1.Text = Format(Now, "hh:mm"):卷标的文本= 10:26(或任何时间)

Label1.Text = Format(Now, "hh:mm tt"):标签的文本=下午10点26

Label1.Text = Format(Now, "dddd dd, MMMM, YYYY"):卷标的文本=周四21月, 2014(或任何日期)

+0

请确保使用正确的格式(内联代码反引号),因为它使您的答案更具可读性。 [帮助](http://stackoverflow.com/help)并测试编辑器工具栏,看看有什么可能。 – TimWolla

1
Label1.Text = Now.ToShortTimeString.ToString() (10:26 PM) 

Label1.Text = Now.ToLongTimeString.ToString() (10:26:30 PM) 
0

试试这个...

Dim TimeNow As String 
    TimeNow = TimeOfDay.ToString("h:mm:ss tt") 
相关问题