Thursday, January 29, 2009

To SET date and time format settings programatically.

I came up with this unique requirement of having to SET date and time format settings programatically. It is a bit tricky to do this using vbscript.
I googled a bit to find a snippet which really works :)
It is possible to play with it here and there to get the required format.

'=======================
Private Const LOCALE_SDATE = &H1F
Private Const LOCALE_STIMEFORMAT = &H1003
Private Const WM_SETTINGCHANGE = &H1A
Private Const HWND_BROADCAST = &HFFFF&

Private Declare Function SetLocaleInfo Lib "kernel32" Alias "SetLocaleInfoA" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String) As Boolean

Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

Private Declare Function GetSystemDefaultLCID Lib "kernel32" () As Long

Private Declare Function GetLocaleInfo Lib "kernel32" Alias "GetLocaleInfoA" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String, ByVal cchData As Long) As Long

Public Function SetDateTime() As Boolean
Dim dwLCID As LongdwLCID = GetSystemDefaultLCID()
If SetLocaleInfo(dwLCID, LOCALE_SDATE, "dd/MM/yyyy") = False Then
SetDateTime = False
Exit Function
End If
If SetLocaleInfo(dwLCID, LOCALE_STIMEFORMAT, "HH:mm:ss") = False Then
SetDateTime = False
Exit Function
End If
PostMessage HWND_BROADCAST, WM_SETTINGCHANGE, 0, 0
SetDateTime = True
End Function
'=======================
Change the LOCALE_SDATE variable value to get the desired results for Date format and LOCALE_STIMEFORMAT variable value for Time format.

3 comments:

Sathish said...

Good one.
How can we change date of remote machine using vbscript ?

Himesh said...

Its very easy Sathish...
Google a bit

india said...

Good Work Dude.Thanks for sharing these kind of valuable experiences.

In My case I used 'TimeValue' function to converte it into hh:mm:ss and datetiem format.