日期时间怀疑哪种格式通过 [英] Datetime doubt which format passed through

查看:75
本文介绍了日期时间怀疑哪种格式通过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Program
    {

        static void Main(string[] args)
        {
            string date = "19890428";
            DateTime dateTime;
            string[] format = { "MMddyyyy", "ddMMyyyy", "yyyyMMdd", "yyyyddMM" };
            if (DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture,
                   DateTimeStyles.None, out dateTime))
            {
                Console.WriteLine( "yes" );
            }

            Console.ReadLine();

        }
    }


I get output "yes" -- by looking at the format i can know that it is yyyyMMdd so it is passed in if condition.

Is there a way to know at runtime that which format is passed.
We are consuming a webservice and the format that we are getting are not sure.It always comes as string. I don't want to do if else to check which format got passed and convert accordingly as below.  

var x = DateTime.ParseExact(cd13, "yyyyddMM", CultureInfo.InvariantCulture);

Kindly suggest.

推荐答案

DateTime.TryParseExact的多格式版本不会给你任何有关哪种格式匹配的信息 - 如果匹配任何一种格式,则返回true;如果没有,则返回false。



如果您需要知道它是哪种格式,你唯一的方法就是依次用每种格式重复调用它,直到你得到一个匹配,或用完格式字符串。



但是......这很危险 - 您应该使用用户输入的文化(或者更好地提示他分别为日,月和年)。使用您的代码,05122012将始终被识别为5月12日,即使用户打算在12月5日。
The "multiple format" version of DateTime.TryParseExact does not give you any information on which format was matched - it just returns true if any one was matched, and false if none of them were.

If you need to know which format it was, your only method is to call it repeatedly with each format in turn until you either get a match, or run out of format strings.

But...that's dangerous - you should be using the Culture that the user is entering in (or better prompt him for the day, month, and year separately). With your code, "05122012" will always be recognised as the 12th of May, even if the user intended the 5th of December.


这篇关于日期时间怀疑哪种格式通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆