You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Basic中如何将字符串日期转换为指定格式并读写文件?

问题解决方法

你遇到的Format函数输出#号的问题,是因为FileData(2)是字符串类型,而####/##/##是数字格式符,仅对数值类型生效,字符串用这个格式会因无法解析为数字而显示#。下面提供两种靠谱的解决思路:

方法一:直接截取字符串(适合固定8位YYYYMMDD格式)

因为输入是固定长度的日期字符串(如"20230131"),可以直接拆分拼接:

Dim Start As String
Dim FileData()
FileData = myReader.ReadFiles()
Start = FileData(2)

' 先转成YYYY/MM/DD格式
Dim yyyyMmDd As String = $"{Left(Start, 4)}/{Mid(Start, 5, 2)}/{Right(Start, 2)}"
' 再转成DD/MM/YR(两位年份)格式
Dim ddMmYr As String = $"{Right(Start, 2)}/{Mid(Start, 5, 2)}/{Right(Left(Start, 4), 2)}"

myWriter.WriteLine("A004 " & ddMmYr)

方法二:转为DateTime类型后格式化(更严谨,可验证日期合法性)

先把字符串转成DateTime对象,再用日期格式符格式化,还能自动处理无效日期的情况:

Dim Start As String
Dim FileData()
FileData = myReader.ReadFiles()
Start = FileData(2)

' 先将字符串转为DateTime
Dim dateValue As DateTime
If DateTime.TryParseExact(Start, "yyyyMMdd", Nothing, Globalization.DateTimeStyles.None, dateValue) Then
    ' 转成DD/MM/YR格式(这里"yy"对应两位年份)
    Dim ddMmYr As String = dateValue.ToString("dd/MM/yy")
    myWriter.WriteLine("A004 " & ddMmYr)
Else
    ' 处理无效日期的情况,比如输出原字符串或错误提示
    myWriter.WriteLine("A004 无效日期: " & Start)
End If

补充说明

  • 如果你需要的YR是四位年份,把格式符改成"dd/MM/yyyy"即可;
  • 方法二的优势是能过滤非法日期(比如"20230230"这种不存在的日期),避免输出错误格式。

内容的提问来源于stack exchange,提问作者Nate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 03:20:15