简体   繁体   English

DateTime.TryParse 没有文化

[英]DateTime.TryParse without Culture

I want to check whether date is valid to parse.我想检查日期是否可以有效解析。 But when i tried with below logic, it is falling for the valid date (eg: ‎3‎/‎10‎/‎2020).但是,当我尝试使用以下逻辑时,它正在落入有效日期(例如: 3 / 10 / 2020)。 I am receiving this myDate via ajax request.我通过 ajax 请求收到这个 myDate。

I tried by changing culture, but still, it didn't work我尝试通过改变文化,但仍然没有奏效

DateTime validMyDate;
if(DateTime.TryParse(myDate, CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out validMyDate)){}

Appriciate your kind help感激您的帮助

Edited: Please find the ajax code at here编辑:请在此处找到 ajax 代码

//fileds

<input name="StartDate" id="StartDate" type="hidden" value="3/10/2020 12:00:00 AM"  data-val="true">
<input name="EndDate" id="EndDate" type="hidden" value="3/26/2020 12:00:00 AM"  data-val="true">

// ajax call
$.get(domainUrl + "Controller/Action",
            {
              strartDate: dateFormatter.fomat($('#StartDate').val(), "mm/dd/yyyy"),
                endDate:  dateFormatter.fomat($('#EndDate').val(), "mm/dd/yyyy");
            },
            function (result) {

            }).fail(function (error) {

            });


// date formatter
var dateFormatter = {
    fomat: function (date, format) {
        var year = date.getFullYear();
        var month = date.getMonth() < 10 ? '0' + date.getMonth() : date.getMonth();
        var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
        var newDate;
        switch (format) {
            case "dd/mm/yyyy": newDate = day + "/" + month + "/" + year;
                break;            
            default: newDate = year + "-" + month + "-" + day;
        }
        return newDate;
    }
}       

Please note : this format function is added, because .val() didn't work at the begging, so i format it again to check whether it is working.请注意:添加了这个格式化函数,因为.val()在乞讨时不起作用,所以我再次格式化它以检查它是否有效。

This code definitely works:这段代码绝对有效:

if (DateTime.TryParseExact("3/10/2020","d/M/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime validStartDate))
{
}

But there is something rotten with your string.但是你的绳子上有些东西烂了。 If I copy "3/10/2020" from your comment above, it doesn't work.如果我从上面的评论中复制“3/10/2020”,则不起作用。 If I write it myself it works.如果我自己写它就可以了。 Your string must be in some weird encoding, but I can't put my finger on what it is.您的字符串必须采用某种奇怪的编码,但我无法确定它是什么。

EDIT: To remove the invisible characters do this:编辑:要删除不可见字符,请执行以下操作:

var str = "‎3‎/‎10‎/‎2020";
str = str.Replace("\u200E","");
if (DateTime.TryParseExact(str,"d/M/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime validStartDate))
{
}

but it will be a hack.但这将是一个黑客。 The problem should be changed at the other end.问题应该在另一端改变。

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

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