在VB .NET中处理日期 [英] Handling dates in VB .NET

查看:60
本文介绍了在VB .NET中处理日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以通过代码(或逻辑)帮助我解决日期错误"问题吗?我在程序中遇到的问题这是一个场景.

1.我的系统的语言环境为en_US,因此将日期显示为MM/DD/YYYY

2.我的程序尝试从一个csv文件导入,在该文件中它对字段进行测试以在加载其余数据之前检查有效日期.

3.如果文件中的日期格式为DD/MM/YYYY,则测试将失败,因此不会加载数据.这是错误.

我想要代码测试csv文件中的日期字符串,该字符串可以识别任何日期格式(语言环境).

有帮助吗?谢谢-Philip


pkkltd

Can anyone help me with code (or logic) to deal with a "date bug" that I have encountered in my program. Here is a scenario.

1. My system has a locale of en_US and therefore displays the date as MM/DD/YYYY

2. My program tries to import from a csv file in which it carries out tests on a field to check for a valid date before loading the rest of the data.

3. If the date in the file is in the format DD/MM/YYYY the test fails and therefore the data is not loaded. THIS is the bug.

I would like code to test for the date string in the csv file that will recognise any date format (locale).

Any help? Thanks - Philip


pkkltd

推荐答案

我认为最好的选择是在Date类上使用内置的TryParseExact函数.可能会漏掉一些无效的函数,但可能其中一个会使前两位大于12.当函数第一次出现失败时,您可以抛出异常并转储已解析的数据.

该函数需要一个IFormatProvider实现对象-可以简单地是一个CultureInfo对象,如下所示.
I think your best bet is to use the built-in TryParseExact function on the Date class.  There may be some that slip through that are invalid but the odds are that one of them will have the first two digit be larger than 12.  When the first occurrence of the function fails then you can throw the exception and dump the already parsed data.

This function requires an IFormatProvider implementing object -- this can simply be a CultureInfo object as shown below..
 
 
        Dim value As String = "12/30/2009"
        Dim d As Date
        If Date.TryParseExact(value, "MM/dd/yyyy", New Globalization.CultureInfo("en-US"), Globalization.DateTimeStyles.None, d) Then
            MsgBox("The value of " & d.ToString("MM/dd/yyyy") & " is good")
        Else
            MsgBox("The value is not in the correct format")
        End If


首先运行此程序(会很好),然后将日期更改为"2009年30月12日".它将失败.此逻辑将在您的csv解析器中(或从其中调用为函数),并将用于测试所解析的每个日期值.




Run this first (it will be good), then change the date to "30/12/2009" and it will fail.  This logic would be in your csv parser (or called as a function from it) and would be used to test every date value that is parsed.
 

 


这篇关于在VB .NET中处理日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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