VB.NET日期/时间格式

时间:2018-10-01 12:59:45

标签: vb.net

我需要访问一个文件,该文件会根据当前星期更改其名称。因此,例如,本周文件名为“ 9月24日某事某周。xlsm”,我有一段代码如下:

    Dim weekOf As Date = Date.Today
    While (weekOf.DayOfWeek <> DayOfWeek.Monday)
        weekOf = weekOf.AddDays(-1)
    End While

    If IO.File.Exists("Something Something Week of " & weekOf.ToString("m", CultureInfo.CreateSpecificCulture("en-us")) & ".xlsm") Then
        Console.WriteLine(weekOf.ToString("m", CultureInfo.CreateSpecificCulture("en-us")))
        GetChartFromExcelWorksheet("Something Something Week of " & weekOf.ToString("m", CultureInfo.CreateSpecificCulture("en-us")) & ".xlsm", "Materials", 1, "msDeliveries")
    Else
        MsgBox("ERROR! File improperly named.")
    End If

在我的机器上,它运行良好。 weekOf.ToString(“ m”)始终返回完整的月份和日期(即9月24日)。在正在运行的系统上,它似乎是随机触发的。它会在9月24日停留一段时间,然后突然切换到9月24日。导致错误,让我头疼。

我最明显的第一点是,运行此应用程序的PC的日期格式与我的开发计算机不同。不,不是吗。两种系统都设置为显示相同的日期格式。

因此,我做了一些研究,并添加了CultureInfo.CreateSpecificCulture(“ en-us”)标志以尝试强制使用该格式。仍然没有喜悦。

希望一个比我聪明的人可以告诉我我做错了什么。

1 个答案:

答案 0 :(得分:0)

如评论中所述,您需要更加严格才能实现好的解决方案。 Microsoft文档页面上有一篇不错的文章,内容是Date and Time Strings。魔术线如下:

Dim CustomDate = weekOf.ToString("MMMM dd yyyy")
'the output will be for example "June 10 2020".

对于日期格式,它们是几个自定义格式说明符。 MMMM代表月份的全名。 dd代表数字中的月份,yyyy代表数字中的年份……仅列举一些可用的specifer。因此您的最终代码可能如下所示:

Dim weekOf As Date = Date.Today
While (weekOf.DayOfWeek <> DayOfWeek.Monday)
    weekOf = weekOf.AddDays(-1)
End While
Dim CustomDate = weekOf.ToString("MMMM dd yyyy")
'Just change the pattern if you dont need the year.
If IO.File.Exists("Something Something Week of " & CustomDate & ".xlsm") Then
    Console.WriteLine(CustomDate )
    GetChartFromExcelWorksheet("Something Something Week of " & CustomDate & ".xlsm", "Materials", 1, "msDeliveries")
Else
    MsgBox("ERROR! File improperly named.")
End If