简体   繁体   English

如何将DateTime转换为字符串

[英]How to Convert DateTime to String

The ra.Value in the while loop sometimes is DateTime type and unfortunately the .ToString() method is not enough to convert it to string. while循环中的ra.Value有时是DateTime类型,不幸的是.ToString()方法不足以将其转换为字符串。 What I should change on my code, to recognize when ra.Value is DateTime type and convert it to String. 我应该在代码上进行哪些更改,以识别ra.Value何时为DateTime类型并将其转换为String。 Now I have the exception that conversion from type 'DateTime' to type 'String' is not valid. 现在,我有一个例外,即从“ DateTime”类型到“ String”类型的转换无效。

With ro.Attributes.GetEnumerator
    While .MoveNext
        Dim ra As ReportAttribute = CType(.Current, ReportAttribute)
        Dim lstrColumnReportObj As Integer = ra.Column
        Dim lstrValueReportObj As String = ra.Value.ToString()
        lstrParTable(lstrColumnReportObj) = lstrParTable(lstrColumnReportObj) + lstrValueReportObj
    End While
End With

Thank you. 谢谢。

The simple solution that you are probably looking for is this: 您可能正在寻找的简单解决方案是:

With ro.Attributes.GetEnumerator
    While .MoveNext
        Dim ra As ReportAttribute = CType(.Current, ReportAttribute)
        Dim lstrColumnReportObj As Integer = ra.Column
        Dim lstrValueReportObj As String = Nothing
        If TypeOf ra.Value Is Date Then
            lstrValueReportObj = ra.Value.ToString("d MMM yyyy")
        Else
            lstrValueReportObj = ra.Value.ToString()
        End If
        lstrParTable(lstrColumnReportObj) = lstrParTable(lstrColumnReportObj) + lstrValueReportObj
    End While
End With

However, this does smack of bad practice and you may want to reconsider your overall design. 但是,这确实存在一些不良做法,您可能需要重新考虑整体设计。 Usually, when you have to start putting in special logic for certain types, like that, it's usually a sign that you could be doing it in a better way. 通常,当您必须开始为某些类型添加特殊逻辑时,通常表明您可能会以更好的方式进行操作。 For instance, what will happen when you start needing custom formatting for other types as well. 例如,当您也开始需要其他类型的自定义格式时,将会发生什么。 Once you have more than a handful of exceptions, it's going to get unwieldy and the code will be brittle (prone to bugs). 一旦您拥有少数例外,它将变得笨拙,并且代码将变得脆弱(容易出现错误)。

Also, I feel obligated to mention that hungarian notation is discouraged in .NET. 另外,我不得不提到在.NET中不鼓励使用匈牙利表示法。 If you are required to use it by your employer, that's fine, but otherwise, I'd recommend reading through the official Microsoft naming guidelines . 如果您的雇主要求您使用它,那很好,但是否则,我建议您仔细阅读Microsoft官方命名指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM