5

C#/Winform では、ユーザーが入力した場合、文字列を日付に解析できます。dd/mm/yyyy

DateTime.Parse(date).ToString();

スラッシュなしで解析できるようにしたいと思います (たとえば、datagridview や DateTimePicker のように)。

01022012に解析する必要があります01/02/2012

で解析する方法を知っている人はいDateTime.Parseますか?

これが私のコードです:

    private void dataGridView_BadgeService_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        if (dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateDebut" || dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateFin")
        {
            string date = Convert.ToString(e.FormattedValue).Trim();

            if (date.Length > 0)
            {
                try
                {
                    DateTime _date;
                    DateTime.TryParseExact(date, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out _date);
                    date = _date.ToShortDateString();
                    dataGridView_BadgeService.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = date;
                }
                catch
                {
                   MessageBox.Show("Merci de saisir une date, ou laissez cette zone vierge", "Action-Informatique", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                   e.Cancel = true;
                }
            }
        }

    }

例外メッセージは次のとおりです。

ここに画像の説明を入力

「System.FormatException: 文字列は DateTime 有効として認識されません」

4

2 に答える 2

16

このようなもので試してみてください...

string unslashedValue = "01022012"
DateTime date;
DateTime.TryParseExact(unslashedValue, "ddMMyyyy", 
                       CultureInfo.InvariantCulture, DateTimeStyles.None, date);

...そして、date変数を使用すると、必要なのは...

string slashedValue = date.ToString("dd/MM/yyyy");
于 2013-06-27T13:31:29.863 に答える
3

HuorSwords は間違っていません(入力値としての使用以外string) が、答えは質問に厳密には答えていません: 要求どおりに日付を表​​示するには、事実の後に文字列にフォーマットする必要があります:

DateTime date = DateTime.ParseExact(input, 
  "ddMMyyyy", CultureInfo.InvariantCulture);
string formattedDate = date.ToString("dd/MM/yyyy");
于 2013-06-27T13:34:57.547 に答える