Unable to convert a string to an integer variable from DateTaken attribute on a JPG file

前端 未结 2 1158
萌比男神i
萌比男神i 2021-01-16 04:49

I have a script which is using the EXIF data from a JPG file to find the DateTaken value. Once found, place the data in $Year and $Month

相关标签:
2条回答
  • 2021-01-16 05:30

    A better approach to working with dates is to convert the date string to an actual DateTime object, which provides all the information you're looking for:

    $culture = [Globalization.CultureInfo]::InvariantCulture
    $pattern = 'dd\/MM\/yyyy'
    
    $datestring = $objFolder.GetDetailsOf($File, 12).Split(' ')[0]
    $datetaken  = [DateTime]::ParseExact($datestring, $pattern, $culture)
    
    $year      = $datetaken.Year
    $month     = $datetaken.Month              # month (numeric)
    $monthname = $datetaken.ToString('MMMM')   # month name
    

    Assuming that the date is followed by a time in the format HH:mm:ss you could extend the code to handle the time as well:

    $culture = [Globalization.CultureInfo]::InvariantCulture
    $pattern = 'dd\/MM\/yyyy HH:mm:ss'
    
    $datestring = $objFolder.GetDetailsOf($File, 12)
    $timestamp  = [DateTime]::ParseExact($datestring, $pattern, $culture)
    
    $year      = $timestamp.Year
    $month     = $timestamp.Month              # month (numeric)
    $monthname = $timestamp.ToString('MMMM')   # month name
    $hour      = $timestamp.Hour
    ...
    
    0 讨论(0)
  • 2021-01-16 05:41

    The date-and-time string returned by $objFolder.GetDetailsOf($File, 12) contains invisible control characters[1], for reasons unknown to me.

    You can strip them as follows, after which your code should work:

    # Remove the formatting control characters from the string, by replacing
    # all instances of Unicode character category \p{Cf} with the empty string.
    # For more info on Unicode categories, see http://www.regular-expressions.info/unicode.html
    $dateTimeStr = $objFolder.GetDetailsOf($File, 12) -replace '\p{Cf}'
    
    [int] $yeartaken = $dateTimeStr.Split("/")[2].Split(" ")[0]
    [int] $month = $dateTimeStr.Split("/")[1]
    $monthname = (Get-Culture).DateTimeFormat.GetMonthName($month)
    

    As an aside, on a general note: Ansgar Wiecher's answer shows more robust date-time string parsing techniques.


    [1] In my test file's metadata I found instances of Unicode control characters U+200E (LEFT-TO-RIGHT MARK) and U+200F (RIGHT-TO-LEFT MARK)

    0 讨论(0)
提交回复
热议问题