【问题标题】:Custom formatting including dates自定义格式,包括日期
【发布时间】:2011-04-11 20:53:10
【问题描述】:

在我的应用程序中,我向用户展示了一个选项来自定义生成的文件的名称。程序读取的格式字符串类似于"yyyyMMdd-%1-%2-%3-%4",用户可以根据自己的喜好自定义。

在这种情况下,日期的格式是yyyyMMdd%1 是行程编号,如 1000P,%2 是 PTTTT 等源代码,%3 是 PHYUD 等目的地代码,@987654326 @ 是二级停止代码,如 YYYY123。

我在将实际数据和格式设置为自定义字符串时遇到问题。我相信它是我遇到的日期格式。到目前为止我有

sOut = txtFormatPattern.Text
sOut = sOut.Replace("%1", "1000P")
sOut = sOut.Replace("%2", "PTTTT")
sOut = sOut.Replace("%3", "PHYUD")
sOut = sOut.Replace("%4", "YYYY123")

sOut = myDate.ToString(sOut) 'date is July 01, 2007

输出为“20070701-#1000P-PTTTTP12YUD (YYYY123)” 显然这里的问题是我的最后一次转换。该字符串包含在 PHYUD 中专门表示日期的一部分的关键字符。所以我的问题是如何让我的用户灵活地按照他们的意愿格式化输出,然后正确转换?

agp

【问题讨论】:

    标签: vb.net date replace format


    【解决方案1】:

    我想用上面提到的对应物替换标记,但还包括一些日期和时间的灵活性。我通过执行以下操作解决了这个问题:

    'first replace the tokens by escaping the % character and number so that the
    'date/time formatting ignores it
    sOut = txtFormatPattern.Text
    sOut = sOut.Replace("%1", "\%\1")
    sOut = sOut.Replace("%2", "\%\2")
    sOut = sOut.Replace("%3", "\%\3")
    sOut = sOut.Replace("%4", "\%\4")
    
    'now apply the date/time formatting as set by the user. the end result strips out
    'the escape characters and ignores them for date/time formatting
    sOut = myDate.ToString(sOut) 'date is July 01, 2007
    
    'we should now have applied the date/time formatting and still have the original
    'tokens so just replace
    sOut = sOut.Replace("%1", "1000P")
    sOut = sOut.Replace("%2", "PTTTT")
    sOut = sOut.Replace("%3", "PHYUD")
    sOut = sOut.Replace("%4", "YYYY123")
    

    使用此例程,用户可以将格式化字符串设置为“yyyyMMdd-%1-%2-%3-%4”,结果输出将为“20070701-#1000P-PTTTT-PHYUD-YYYY123”

    这应该适用于用户可以在选项中设置的任何日期/时间格式变体,因为有效标记总是由 %n 表示。

    agp

    【讨论】:

    • 请编辑您的原始问题以添加信息。这不是一个讨论论坛,所以我们不会“回复主题”。
    • 不确定这意味着什么。我添加了我认为需要的尽可能多的信息。你的意思是如果我找到了将其添加到原始问题的答案,或者我可以像在这里一样添加它吗?
    【解决方案2】:

    您可以使用String.Format 做您想做的事。花括号内的每个部分都是您传递给函数的参数的占位符。

    或者,您可以在一个冒号后跟另一个特定于参数的格式化字符串。

    sOut = String.Format("{0:yyyyMMdd} {1} {2} {3} {4}", myDate, "1000P", "PTTTT", "PHYUD", "YYYY123")
    

    【讨论】:

    • 感谢您的提示。如果日期的格式保持一致,我可以这样做,但恐怕不会。用户可以选择使用他们想要的几乎任何格式。例如像 yyyy-%1-MM-%2-dd (%3) 这样的东西。你的小费虽然让我深思。谢谢。
    猜你喜欢
    • 2021-05-15
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2021-08-06
    • 2011-03-01
    相关资源
    最近更新 更多