2012-06-12 215 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") 
相關問題