繁体   English   中英

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

[英]How to Change the Date Format from MM/dd/yyyy to dd-MM-yyyy?

我想在创建代码的当前日期中添加天数,但它显示错误字符串未被识别为有效的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");
    }

亲爱的我,我正在更新错误,感谢您的答复,这里的错误是帮助 在此处输入图片说明

使用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/QA/DotNet/CSharp/how-to-check-valid-date-in-c/20271

您的代码似乎正确,但是您的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)适合!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM