Conversing date with different culture

Welcome Forums General PowerShell Q&A Conversing date with different culture

This topic contains 4 replies, has 4 voices, and was last updated by

 
Participant
3 years, 7 months ago.

  • Author
    Posts
  • #24922

    Participant
    Points: 0
    Rank: Member

    Hi,

    I have a problem with conversing a string variable in to a different data time variable.

    My string is something like this:

    Sun Apr 12 14:37:28 2015 – meaning – abbreviated day, abbreviated month, day number, 24 hour, year

    The main problem is with culture. The string uses english names and my powershell uses polish names so when i try to format or parse the string i cannot read properly the abbreviated day and month 🙁

    Second thing, important I think, I only need this string to put in date so I can manipulate the date, for example subtract 7 days and then again put in string and read the value 7 days before.

    Any help ?

  • #24923

    Participant
    Points: 1
    Rank: Member

    This is how I am dealing with this:

    #Change locale for the current Thread to en-US
    function Set-Culture([System.Globalization.CultureInfo] $culture)
    {
        [System.Threading.Thread]::CurrentThread.CurrentUICulture = $culture
        [System.Threading.Thread]::CurrentThread.CurrentCulture = $culture
    }
    
    Set-Culture en-US

    This function changes the culture from this point on to en-US.
    If you want to change it back later in the script, you run the function again using the polish culture.

  • #24981

    Participant
    Points: 0
    Rank: Member

    When i run Your script and then get-culture i still get my culture and still i cannot read abbreviated days.

    edit:
    but on the other hand when I use get-date I get now in english form.

  • #24984

    Participant
    Points: 1
    Rank: Member

    Is this what you are looking for? If so, the date format string here assumes that the day will be in two digit form for days less than 10 (e.g. it expects 09 instead of just 9) . The date format string can be modified to expect single date values by changing dd to d.

    [datetime]::ParseExact("Sun Apr 12 14:37:28 2015","ddd MMM dd HH:mm:ss yyyy",[CultureInfo]("en-US"))

    And concerning the date subtraction:

    PS T:\1> $date = [datetime]::ParseExact("Sun Apr 12 14:37:28 2015","ddd MMM dd HH:mm:ss yyyy",[CultureInfo]("en-US"))
    PS T:\1> $date.AddDays(-7)
    
    Sunday, April 5, 2015 2:37:28 PM
    
    
    PS T:\1> $date.AddDays(-7).Date
    
    Sunday, April 5, 2015 12:00:00 AM
  • #113563

    Participant
    Points: 0
    Rank: Member

    It is interesting to read your blog post and I am going to share it with my friends.

    Herbew Fentos

The topic ‘Conversing date with different culture’ is closed to new replies.