Jump to content

Universal Date Format Conversion


GreenCan
 Share

Recommended Posts

This is an example of a universal date converter from your PC local date format to any format you could need to use.

I couldn't find any good solution on the forum, so I re-engineered an example of DaRam.

This should work with any regional setting date format.

The script reads the Local date format in your registry setting.

RegRead("HKCU\Control Panel\International", "sShortDate")

I hope you can use it.

GreenCan

#cs

    Description:    Universal date format converter
                    Converts the (default regional setting) PC Date format into any other specified date format:
                    - convert date into another date format (for example ddd dd MMMM, yyyy)
                    - convert date into day (d or dd)
                    - convert date into month ( m, mm or mmm)
                    - convert date into year (yy or yyyy)
            
    Parameter(s):   $InputDate  Input date 
                    $DateFmt        - Format of input date (optional), if omitted, will return date in mm/dd/yyyy

    Requirement(s): <DateCalc.au3>
                    The udf is included in this script 
    
    Return Value(s):On Success      - Date in in requested format
    
                    On Error        - @ERROR 1 (input date badly formatted)
                                    -  Error Message

    Author(s):      GreenCan
    
    Note(s):        Part of source code was borrowed from the Date conversion example provided by DaRam
                        http://www.autoitscript.com/forum/index.php?showtopic=76984&view=findpost&p=557834
                    DateCalc.au3 (_DateCalc udf) by Sean Hart
                        http://www.autoitscript.com/forum/index.php?showtopic=14084&view=findpost&p=96173

    Syntax:         DateFormat( $Date , $DateFormat )
    
    Example:        DateFormat( _NowCalcDate() , "dd-MM-yyyy" )

#ce
#include <Date.au3>
#include <DateTimeConstants.au3>
#include <GUIConstants.au3>
;#include <DateCalc.au3>

Global $sDateFormat = RegRead("HKCU\Control Panel\International", "sShortDate") ; This is the date format of your PC

; example 1: Using GUICtrlCreateDate in a GUI
$Form1 = GUICreate("PC DateFormat: " & $sDateFormat, 290, 112, 193, 115)
$Label1 = GUICtrlCreateLabel("Date:", 8, 8, 90, 17)
$Input1 = GUICtrlCreateDate(_Date_Time_GetLocalTime(),  100, 8, 180, 21,$DTS_SHORTDATEFORMAT ) ; $DTS_SHORTDATEFORMAT $DTS_LONGDATEFORMAT

$Label2 = GUICtrlCreateLabel("Date Time Format:", 8, 36, 90, 17)
$Input2 = GUICtrlCreateInput("ddd dd MMMM, yyyy", 100, 33, 180, 21)
$Button1 = GUICtrlCreateButton("&Convert", 8, 64, 89, 25, 0)
$Input3 = GUICtrlCreateInput("", 100, 64, 180, 24)
GUISetState(@SW_SHOW)

GUICtrlSetData( $Input3, DateFormat( GUICtrlRead($Input1), GUICtrlRead($Input2) ) )

While 1
    Switch GUIGetMsg()
    Case $GUI_EVENT_CLOSE
         ExitLoop
    Case $Button1
         GUICtrlSetData( $Input3, DateFormat( GUICtrlRead($Input1), GUICtrlRead($Input2) ) )
    EndSwitch
Wend

; Example 2: Direct conversion (make sure that the input date is in the PC sShortDate format, see your local settings)
$Date = "05/12/2009"
ConsoleWrite ( DateFormat( $Date , "dd-MM-yyyy" ) & @CR)
ConsoleWrite ( DateFormat( $Date , "MMM" ) & @CR)
ConsoleWrite ( DateFormat( $Date , "d" ) & @CR)
ConsoleWrite ( DateFormat( $Date , "yy" ) & @CR)

; Example 3: Error simulation
$NewDate = DateFormat( "35/12/2009" , "dd-MM-yyyy" )
If @error Then
    ConsoleWrite ( $NewDate & @CR)  
Else
    ConsoleWrite ( $NewDate & @CR)
EndIf

#FUNCTION# ==============================================================
Func DateFormat($InputDate, $DateFmt = "mm/dd/yyyy")
    If StringLen($InputDate) < 6 Then 
        SetError (1)
        Return "Invalid Date" ; ddmmyy = 6
    EndIf
    If $DateFmt = "" Then $DateFmt = "dd/mm/yyyy"
    Local $DateValue = _DateCalc ($InputDate,$sDateFormat) ; convert the date to yyyy/mm/dd
    $DateValue = StringSplit($DateValue, "/")
    If @error Then 
        SetError (1)
        Return "Invalid Date " & $InputDate
    EndIf
    If $DateValue[0] < 3 Then ; less than 3 parts in date not possible
        SetError (1)
        Return "Invalid Date " & $InputDate
    EndIf
    If Int(Number($DateValue[1])) < 0 Then 
        SetError (1)
        Return "Invalid Year in Date"       
    EndIf
    If Int(Number($DateValue[2])) < 1 Or Int(Number($DateValue[2])) > 12 Then
        SetError (1)
        Return "Invalid Month in Date"
    EndIf
    If Int(Number($DateValue[3])) < 1 Or Int(Number($DateValue[3])) > 31 Then 
        SetError (1)
        Return "Invalid Day in Date"
    EndIf
    
    If Int(Number($DateValue[1])) < 100 Then $DateValue[1] = StringLeft(@YEAR,2) & $DateValue[1]
    $InputDate = $DateFmt
    $InputDate = StringReplace($InputDate, "d", "@") ; Convert All Day References to @
    $InputDate = StringReplace($InputDate, "m", "#") ; Convert All Month References to #
    $InputDate = StringReplace($InputDate, "y", "&") ; Convert All Year References to &
    $InputDate = StringReplace($InputDate, "&&&&", $DateValue[1])                       ; Century and Year
    $InputDate = StringReplace($InputDate, "&&", StringRight($DateValue[1],2))          ; Year Only
    $InputDate = StringReplace($InputDate, "&", "")   ; Discard leftover Year Indicator
    $InputDate = StringReplace($InputDate, "####", _DateMonthOfYear($DateValue[2], 0))  ; Long Month Name
    $InputDate = StringReplace($InputDate, "###", _DateMonthOfYear($DateValue[2], 1))   ; Short Month Name
    If StringLen($DateValue[1]) < 2 Then
        $InputDate = StringReplace($InputDate, "##", "0" & $DateValue[2])                ; Month Number 2 Digit
    Else
        $InputDate = StringReplace($InputDate, "##", $DateValue[2])                      ; Month Number 2 Digit
    EndIf
    $InputDate = StringReplace($InputDate, "#", int($DateValue[2]))                     ; Month Number
    $iPos = _DateToDayOfWeek($DateValue[1], $DateValue[2], $DateValue[3])               ; Day of Week Number
    $InputDate = StringReplace($InputDate, "@@@@", _DateDayOfWeek($iPos, 0))            ; Long Weekday Name
    $InputDate = StringReplace($InputDate, "@@@", _DateDayOfWeek($iPos, 1))             ; Short Weekday Name
    $InputDate = StringReplace($InputDate, "@@", $DateValue[3])                         ; Day Number 2 Digit
    $InputDate = StringReplace($InputDate, "@", int($DateValue[3]))                     ; Day Number
    
    Return $InputDate
EndFunc ;==>DateFormat
#FUNCTION# ==============================================================
;===============================================================================
;
; Description:      Returns the Date [and time] in format YYYY/MM/DD [HH:MM:SS],
;                   give the date / time in the system or specified format.
; Parameter(s):     $sSysDateTime   - Input date [and time]
;                   $dFormat        - Format of input date (optional)
;                   $tFormat        - Format of input time (optional)
; Requirement(s):   None
; Return Value(s):  On Success      - Date in in format YYYY/MM/DD [HH:MM:SS]
;                   On Error        - @ERROR    - 1 (input date badly formatted)
;                                   - @ERROR    - 2 (input time badly formatted)
; Author(s):        Sean Hart <autoit@hartmail.ca>
; Note(s):          Date format can be provided without any separators only in
;                   the format YYYYMMDD.
;                   If system format is used it is current user format, NOT
;                   default user format (which may be different).
;                   2 digit years converted:    81 - 99 -> 1981-1999
;                                               00 - 80 -> 2000-2080
;
;===============================================================================
#include-once
Func _DateCalc($sSysDateTime, $dFormat = "", $tFormat = "")
    Local $sDay
    Local $sMonth
    Local $sYear
    Local $sHour
    Local $sMin
    Local $sSec
    ;Local $dFormat
    Local $dSep
    ;Local $tFormat
    Local $tSep
    Local $am
    Local $pm
    Local $split1[9]
    Local $split2[9]
    Local $sSysDate
    Local $sSysTime
    Local $isAM
    Local $isPM
    Local $sTestDate

    ; Read default system time formats and separators from registry unless provided
    if $dFormat = "" then
        $dFormat = RegRead ("HKEY_CURRENT_USER\Control Panel\International", "sShortDate")
        $dSep = RegRead ("HKEY_CURRENT_USER\Control Panel\International", "sDate")
    else
        ; Extract separator from date format by finding first non recognised character
        for $x = 1 to StringLen ($dFormat)
            if (not (StringMid ($dFormat, $x, 1) = "y")) AND (not (StringMid ($dFormat, $x, 1) = "m")) AND (not (StringMid ($dFormat, $x, 1) = "d")) then
                $dSep = StringMid ($dFormat, $x, 1)
                ExitLoop
            endif
        next
    endif
    if $tFormat = "" then
        $tFormat = RegRead ("HKEY_CURRENT_USER\Control Panel\International", "sShortDate")
        $tSep = RegRead ("HKEY_CURRENT_USER\Control Panel\International", "sDate")
        $am = RegRead ("HKEY_CURRENT_USER\Control Panel\International", "s1159")
        $pm = RegRead ("HKEY_CURRENT_USER\Control Panel\International", "s2359")
    else
        ; Extract separator from time format by finding first non hour character
        for $x = 1 to StringLen ($tFormat)
            if (not (StringMid ($tFormat, $x, 1) = "h")) then
                $tSep = StringMid ($tFormat, $x, 1)
                ExitLoop
            endif
        next
        $am = "AM"
        $pm = "PM"
    endif
    
    ; Separate date and time if included (make break at first space)
    if StringInStr ($sSysDateTime, " ") then
        $sSysDate = StringLeft ($sSysDateTime, StringInStr ($sSysDateTime, " ") - 1)
        $sSysTime = StringStripWS (StringReplace ($sSysDateTime, $sSysDate, ""), 1)
    else
        $sSysDate = $sSysDateTime
        $sSysTime = ""
    endif
    
    ; Simple check of input date format (look for separators and unexpected non numeric characters)
    $sTestDate = StringReplace ($sSysDate, $dSep, "")
    $sTestDate = "1" & $sTestDate
    if (String (Number ($sTestDate)) <> $sTestDate) then
        SetError (1)
        Return
    endif
    if (StringInStr ($sSysDate, $dSep) = 0) AND ($dSep <> "") then
        SetError (1)
        Return
    endif
    if $sSysTime <> "" then
        $sTestDate = StringReplace ($sSysTime, $tSep, "")
        $sTestDate = StringReplace ($sTestDate, $am, "")
        $sTestDate = StringReplace ($sTestDate, $pm, "")
        $sTestDate = StringReplace ($sTestDate, " ", "")
        $sTestDate = "1" & $sTestDate
        if (StringInStr ($sSysTime, $tSep) = 0) or (String (Number ($sTestDate)) <> $sTestDate) then
            SetError (2)
            Return
        endif
    endif

    ; Break up date components (using format as a template), unless format is YYYYMMDD
    if $dFormat = "YYYYMMDD" then
        $sYear = StringMid ($sSysDate, 1, 4)
        $sMonth = StringMid ($sSysDate, 5, 2)
        $sDay = StringMid ($sSysDate, 7, 2)
    else
        $split1 = StringSplit ($dFormat, $dSep)
        $split2 = StringSplit ($sSysDate, $dSep)
        for $x = 1 to $split1[0]
            if StringInStr ($split1[$x], "M") then $sMonth = $split2[$x]
            if StringInStr ($split1[$x], "d") then $sDay = $split2[$x]
            if StringInStr ($split1[$x], "y") then $sYear = $split2[$x]
        next
    endif
    
    ; Pad values with 0 if required and fix 2 digit year
    if StringLen ($sMonth) = 1 then $sMonth = "0" & $sMonth
    if StringLen ($sDay) = 1 then $sDay = "0" & $sDay
    if StringLen ($sYear) = 2 then
        if $sYear > 80 then
            $sYear = "19" & $sYear
        else
            $sYear = "20" & $sYear
        endif
    endif
    
    ; Break up time components (if given)
    if $sSysTime <> "" then
        ; Look for AM/PM and note it, then remove from the string
        $isPM = 0
        if StringInStr ($sSysTime, $am) then
            $sSysTime = StringReplace ($sSysTime, " " & $am, "")
            $isPM = 1
        elseif StringInStr ($sSysTime, $pm) then
            $sSysTime = StringReplace ($sSysTime, " " & $pm, "")
            $isPM = 2
        endif
        $split1 = StringSplit ($tFormat, $tSep)
        $split2 = StringSplit ($sSysTime, $tSep)
        $sSec = "00"
        for $x = 1 to $split2[0]
            if StringInStr ($split1[$x], "h") then $sHour = $split2[$x]
            if StringInStr ($split1[$x], "m") then $sMin = $split2[$x]
            if StringInStr ($split1[$x], "s") then $sSec = $split2[$x]
        next
        
        ; Clean up time values (change hour to 24h and 0 pad values)
        if ($isPM = 1) and ($sHour = 12) then $sHour = "00"
        if ($isPM = 2) and ($sHour < 12) then $sHour = $sHour + 12
        if StringLen ($sHour) = 1 then $sHour = "0" & $sHour
        if StringLen ($sMin) = 1 then $sMin = "0" & $sMin
        if StringLen ($sSec) = 1 then $sSec = "0" & $sSec
        
        ; Return date with time
        Return $sYear & "/" & $sMonth & "/" & $sDay & " " & $sHour & ":" & $sMin & ":" & $sSec
    else
        ; Return date only
        Return $sYear & "/" & $sMonth & "/" & $sDay
    endif
EndFunc   ;==>_DateCalc
#FUNCTION# ==============================================================

Contributions

CheckUpdate - SelfUpdating script ------- Self updating script

Dynamic input validation ------------------- Use a Input masks can make your life easier and Validation can be as simple

MsgBox with CountDown ------------------- MsgBox with visual countdown

Display Multiline text cells in ListView ---- Example of pop-up or ToolTip for multiline text items in ListView

Presentation Manager ---------------------- Program to display and refresh different Border-less GUI's on a Display (large screen TV)

USB Drive Tools ------------------------------ Tool to help you with your USB drive management

Input Period udf ------------------------------ GUI for a period input

Excel ColorPicker ---------------------------- Color pickup tool will allow you to select a color from the standard Excel color palette

Excel Chart UDF ----------------------------- Collaboration project with water 

GetDateInString ------------------------------ Find date/time in a string using a date format notation like DD Mon YYYY hh:mm

TaskListAllDetailed --------------------------- List All Scheduled Tasks

Computer Info --------------------------------- A collection of information for helpdesk

Shared memory Demo ----------------------- Demo: Two applications communicate with each other through means of a memory share (using Nomad function, 32bit only)

Universal Date Format Conversion -------- Universal date converter from your PC local date format to any format

Disable Windows DetailsPane -------------- Disable Windows Explorer Details Pane

Oracle SQL Report Generator -------------  Oracle Report generator using SQL

SQLite Report Generator -------------------  SQLite Report generator using SQL

SQLite ListView and BLOB demo ---------- Demo: shows how binary (image) objects can be recognized natively in a database BLOB field

DSN-Less Database connection demo --- Demo: ActiveX Data Objects DSN-Less Database access

Animated animals ----------------------------- Fun: Moving animated objects

Perforated image in GUI --------------------- Fun: Perforate your image with image objects

UEZ's Perforator major update ------------- Fun: Pro version of Perforator by UEZ

Visual Crop Tool (GUI) ----------------------- Easy to use Visual Image Crop tool

Visual Image effect (GUI) -------------------- Visually apply effects on an image

 

 

 

Link to comment
Share on other sites

@dantay9 and dmob,

Thanks, happy that you can use this.

GreenCan

Contributions

CheckUpdate - SelfUpdating script ------- Self updating script

Dynamic input validation ------------------- Use a Input masks can make your life easier and Validation can be as simple

MsgBox with CountDown ------------------- MsgBox with visual countdown

Display Multiline text cells in ListView ---- Example of pop-up or ToolTip for multiline text items in ListView

Presentation Manager ---------------------- Program to display and refresh different Border-less GUI's on a Display (large screen TV)

USB Drive Tools ------------------------------ Tool to help you with your USB drive management

Input Period udf ------------------------------ GUI for a period input

Excel ColorPicker ---------------------------- Color pickup tool will allow you to select a color from the standard Excel color palette

Excel Chart UDF ----------------------------- Collaboration project with water 

GetDateInString ------------------------------ Find date/time in a string using a date format notation like DD Mon YYYY hh:mm

TaskListAllDetailed --------------------------- List All Scheduled Tasks

Computer Info --------------------------------- A collection of information for helpdesk

Shared memory Demo ----------------------- Demo: Two applications communicate with each other through means of a memory share (using Nomad function, 32bit only)

Universal Date Format Conversion -------- Universal date converter from your PC local date format to any format

Disable Windows DetailsPane -------------- Disable Windows Explorer Details Pane

Oracle SQL Report Generator -------------  Oracle Report generator using SQL

SQLite Report Generator -------------------  SQLite Report generator using SQL

SQLite ListView and BLOB demo ---------- Demo: shows how binary (image) objects can be recognized natively in a database BLOB field

DSN-Less Database connection demo --- Demo: ActiveX Data Objects DSN-Less Database access

Animated animals ----------------------------- Fun: Moving animated objects

Perforated image in GUI --------------------- Fun: Perforate your image with image objects

UEZ's Perforator major update ------------- Fun: Pro version of Perforator by UEZ

Visual Crop Tool (GUI) ----------------------- Easy to use Visual Image Crop tool

Visual Image effect (GUI) -------------------- Visually apply effects on an image

 

 

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...