开发者

How to change Time Format in VB.NET from 24 to 12?

开发者 https://www.devze.com 2023-02-28 20:39 出处:网络
I am using these codes for displaying time in VB.NET it shows up in 24 hours format besides i need it in 12 hours format

I am using these codes for displaying time in VB.NET it shows up in 24 hours format besides i need it in 12 hours format

System.DateTime.No开发者_运维技巧w.Hour
System.DateTime.Now.Minute
System.DateTime.Now.Second

example:

14:12:42

I need it as :

02:12:42

thanks.


Use String.Format. For example:

String.Format("{0:T}", System.DateTime.Now)           //02:12:42 PM
String.Format("{0:hh:mm:ss}", System.DateTime.Now)    //02:12:42
String.Format("{0:hh:mm:ss tt}", System.DateTime.Now) //02:12:42 PM

Also, this website to be very helpful in summarizing the various ways you can use String.Format. Keep in mind the culture can make a difference on non-custom formats. The first example above using T (Long Time format) works on my US-based PC just fine. But if you say:

String.Format(System.Globalization.CultureInfo.InvariantCulture, _
              "{0:T}", System.DateTime.Now)

You end up with 14:12:42. The latter two examples are custom formats and are not affected by culture.


When using DateTime objects you can actually use the ToString() method and set your format inside it.

string currentTime = System.DateTime.Now.ToString("hh:mm:ss");

Check this msdn article out for more clarity:

http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx


Use the appropriate format string for display.

string formatted = myDateTime.ToString("hh:mm:ss");

I have used a custom format string in this case.


1-Use regex to get first two characters of that string ie from 23:11:59 get 23

2-convert this number to integer type

3-now check it if it is not greater than 12 and if it is subtract 12 from it and by using string.replace replace the old value.


Try This...

  Dim CurTime As String
  CurTime = TimeOfDay.ToString("h:mm:ss tt")
0

精彩评论

暂无评论...
验证码 换一张
取 消