vb怎么在字符串中提取日期

   2025-02-15 9180
核心提示:在VB中,您可以使用正则表达式或者内置的日期和时间函数来提取日期。使用正则表达式提取日期:Imports System.Text.RegularExpre

在VB中,您可以使用正则表达式或者内置的日期和时间函数来提取日期。

使用正则表达式提取日期:
Imports System.Text.RegularExpressionsDim input As String = "今天是2022年1月1日"Dim pattern As String = "(\d{4})年(\d{1,2})月(\d{1,2})日"Dim match As Match = Regex.Match(input, pattern)If match.Success Then    Dim year As Integer = Integer.Parse(match.Groups(1).Value)    Dim month As Integer = Integer.Parse(match.Groups(2).Value)    Dim day As Integer = Integer.Parse(match.Groups(3).Value)    Dim dateValue As New DateTime(year, month, day)    Console.WriteLine(dateValue.ToString("yyyy/MM/dd"))Else    Console.WriteLine("没有找到日期")End If
使用内置的日期和时间函数提取日期:
Dim input As String = "2022年1月1日"Dim formats() As String = {"yyyy年M月d日", "yyyy/M/d"}Dim dateValue As DateTimeIf DateTime.TryParseExact(input, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, dateValue) Then    Console.WriteLine(dateValue.ToString("yyyy/MM/dd"))Else    Console.WriteLine("无法解析日期")End If

以上代码示例中,我们假设输入的字符串中包含"2022年1月1日"这样的日期格式。您可以根据实际情况调整正则表达式或者日期格式。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言