ParseExact-字符串未被识别为有效的DateTime [英] ParseExact - String was not recognized as a valid DateTime

查看:86
本文介绍了ParseExact-字符串未被识别为有效的DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串变量转换为日期时间格式:

I'm trying to convert string variable to datetime format:

[DateTime]::ParseExact($tempdate, 'dd.MM.yyyy', [CultureInfo]::InvariantCulture).ToString('yyMMdd')

$ tempdate 包含格式为 dd.MM.yyyy 的日期,该日期是从Excel文件获取的.

$tempdate contains date in format dd.MM.yyyy which was obtained from an Excel file.

不幸的是,我收到错误消息:

Unfortunately I'm getting error message:

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a
valid DateTime."
At line:1 char:1
+ [DateTime]::ParseExact($tempdate, 'dd.MM.yyyy', [CultureInfo]::Invaria ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

当我使用清除日期"而不是变量时,效果很好.

It works fine when I put 'clean date' instead of variable.

[DateTime]::ParseExact('13.03.2017', 'dd.MM.yyyy', [CultureInfo]::InvariantCulture).ToString('yyMMdd')

此变量有什么问题,或者如何以其他方式将其转换为日期时间?

What is wrong with this variable or how can I convert it to datetime in other way?

推荐答案

当我使用清除日期"而不是变量时,效果很好.

It works fine when I put 'clean date' instead of variable.

这告诉我您的 $ tempdate 首先出问题了,最重要的是它应该是一个字符串,但是您可能会遇到前导或尾随空格的问题.考虑以下.

That tells me something is wrong with your $tempdate first and foremost it should be a string but you could have an issue with leading or trailing whitespace. Consider the following.

PS C:\Users\Bagel> [DateTime]::ParseExact(' 13.03.2017 ', 'dd.MM.yyyy',[CultureInfo]::InvariantCulture)

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At line:1 char:1
+ [DateTime]::ParseExact(' 13.03.2017 ', 'dd.MM.yyyy',[CultureInfo]::In ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

因此,正如我们在评论中发现的那样,这似乎是您的问题.一个简单的 .trim()应该为您处理此问题,前提是您无法控制 $ tempdate 的填充方式(如果这样做,则应首先在此处解决此问题).

So, as we have discovered in comments, this appears to be your problem. A simple .trim() should handle this for you assuming you do not have control over how $tempdate is populated (If you do you should fix the issue there first).

[DateTime]::ParseExact(' 13.03.2017 '.Trim(), 'dd.MM.yyyy',[CultureInfo]::InvariantCulture)

这篇关于ParseExact-字符串未被识别为有效的DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆