如何将日期格式从MM / dd / yyyy更改为dd-MM-yyyy?

时间:2015-12-22 07:00:56

标签: c# asp.net date datetime

我想在当前日期添加我已创建代码的日期但显示错误字符串未被识别为有效的DateTime。我想要这样的日期格式'dd-MM-yyyy'

这是我的剧本

<script>
        function addDate() {
            debugger;
            //Get the entered datevalue
            var enteredDateVal = new moment(document.getElementById("TextBoxStartDate").value);
            //Get the days to add 
            var numberofDays = document.getElementById("TextBoxPredictDays").value
            //Add the days using add method in moment.js
            enteredDateVal.add("days", parseInt(numberofDays));
            //Assign the value in textbox
            document.getElementById("TextBoxPredictedClosing").value = enteredDateVal.format("dd-MM-yyyy");
        }
    </script>

这是我点击按钮的代码

protected void Button9_Click(object sender, EventArgs e)
    {
       // this.TextBoxStartDate ="dd-MM-yyyy";
        DateTime dtval = DateTime.Parse(TextBoxStartDate.Text);
        //Add values here
        DateTime formatteddays = dtval.AddDays(Int16.Parse(TextBoxPredictDays.Text));
        TextBoxPredictedClosing.Text = formatteddays.ToString("dd-MM-yyyy");
    }

我正在为所有亲爱的人更新错误,感谢您的回复 这是错误 enter image description here

2 个答案:

答案 0 :(得分:1)

使用DateTime.ParseExact()从字符串中获取日期对象

protected void Button9_Click(object sender, EventArgs e)
    {
       // this.TextBoxStartDate ="dd-MM-yyyy";
        DateTime dtval = DateTime.ParseExact(TextBoxStartDate.Text, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
        //Add values here
        DateTime formatteddays = dtval.AddDays(Int16.Parse(TextBoxPredictDays.Text));
        TextBoxPredictedClosing.Text = formatteddays.ToString("dd-MM-yyyy");
    }

您还可以将字符串的有效日期检查为

public static bool IsDate(string tempDate)
        {        
            DateTime fromDateValue;
            var formats = new[] { "dd-MM-yyyy" };
            if (DateTime.TryParseExact(tempDate, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out fromDateValue))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

您可以参考日期检查http://www.niceonecode.com/Q-A/DotNet/CSharp/how-to-check-valid-date-in-c/20271

的链接

答案 1 :(得分:0)

您的代码似乎正确,但您的TextBoxStartDate格式不正确。

尝试使用

DateTime myDate = DateTime.ParseExact(TextBoxStartDate.Text, "dd-MM-yyyy",
         System.Globalization.CultureInfo.InvariantCulture);
int numVal = Int32.Parse(TextBoxPredictDays.Text);
myDate.AddDays(numVal);

确保输入格式(dd-MM-yyyy)合适!