如何在 c# 中为 Windows Form App 格式化此 Date 对象?

How do I format this Date object for a Windows Form App in c#?

我正在制作一个简单的 Windows 表单应用程序,它允许用户 select 任何文件并根据他们在文本字段中输入的内容将其重命名为默认格式的名称。

示例:“08_21_2015_DrJohnSmith_HowToSellHomes.mp3”——http://postimg.org/image/ds52o0xu1/

我遇到的问题是我不知道如何设置日期文本框的格式,因此它以这种格式保存文件:

"08_21_2015_DrJohnSmith_HowToSellHomes.mp3"

目前正在以这种格式保存文件:

"Friday, August 21, 2015DrJohnSmith_HowToSellHomes.mp3"

我知道这很容易做到,但我是编程新手,本周才开始学习 C#,因此非常感谢任何帮助。这是我的代码。 link上面的一张图片的表格。

    using System;
    using System.Windows.Forms;
    using System.IO;

    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void selectFileBtn_Click(object sender, EventArgs e)
            {
                openFileDialog1.ShowDialog();
            }

            private void outputFileBtn_Click(object sender, EventArgs e)
            {
                var outputFolder = outputFileTB;
                folderBrowserDialog1.ShowDialog();
                outputFolder.Text = folderBrowserDialog1.SelectedPath;
            }

            private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
            {
                selectFileTB.Text = openFileDialog1.FileName;
            }

            private void saveBtn_Click(object sender, EventArgs e)
            {
                File.Move(selectFileTB.Text, outputFileTB.Text + "/" + dateTimePicker1.Text + speakerTitleTB.Text + firstNameTB.Text + 
                    lastNameTB.Text + "_" + messageTitleTB.Text + ".txt");     
            }
        }
    }

替换

dateTimePicker1.Text

dateTimePicker1.Value.ToString("dd_MM_yyyy", CultureInfo.InvariantCulture)

我看到您正在使用 dateTimePicker1.Text - returns 所选日期值的文本表示 对用户来说 ,这是显然不是你想要的:)

首先,使用dateTimePicker1.Value而不是.Text提取实际的DateTime值,然后使用DateTime.ToString()方法并指定格式字符串以完全控制生成了什么,像这样:

dateTime.ToString( "MM_dd_yyyy", CultureInfo.InvariantCulture )

当使用 .ToString 时(在日期、数字或大多数值上),如果它有一个接受 IFormatInfo 的重载,使用它来显式指定 CultureInfo.InvariantCultureCultureInfo.CurrentCulture(根据当前的 Microsoft FxCop 指南)。如果您希望跨多个平台的行为一致,请务必使用 InvariantCulture,因为如果您使用 CurrentCulture,则输出文本可能不是您所期望的 - 这对于完全自定义的字符串(如 [=)不是问题22=] 但如果你使用像 "g""d" 这样的标准格式字符串,那么你会在不同的机器上看到截然不同的结果。

顺便说一句,我强烈建议您使用 yyyy-MM-dd 而不是 MM_dd_yyyy 作为日期格式,这样文件就可以在文本列表中按时间顺序排序(例如 Windows ' 文件资源管理器),否则文件将按月、日、年排序,这是没有意义的。

最后,请注意,在格式字符串中,MM 用于月,而 mm 用于分钟。

这里有一个参考: