简体   繁体   中英

compare string has all numbers and compare Date

I have string value which has a format "YYYYMMDD_NNN". All are integers except _. I have to validate this string value.

  1. validate all are Integers or not except _

  2. The date value should not be greater than today's date.

  3. It should be same format first 8 are numbers then _ and last three are numbers.

This is what i wrote. is there any better way to improve it or simplified version

string strDate = _htfdate.Substring(0, 8);

if (int.TryParse(strHtfDate, out _))
{
    //ok, do something
    DateTime dt1;

    if(DateTime.TryParse(strHtfDate, out dt1))
    {
        if (dt1 > DateTime.Today)
            //do something
    }
}
else
{
    //not an int
}

i didn't write code to validate last 3 characters here.

string datestring = "20190519_562";
 //check first 8 characters are digit
var rsult = datestring.Take(8).All(char.IsDigit);
 if(rsult == true)
 {
// get last three characters of string 
string dtst= datestring.Substring(datestring.Length - 4);
if(dtst[0]== '_') // check first character is "_"
{
 int length = dtst.Substring(1).Length; // get length of character after "_"
 if(length==3)
{
enter code here
 }

}
 }

You can simply try: It appears the last three are unrelated with the date but the parsing can still happen assuming they are hundredth of a second.

var dateTimeString = "20181230_183";
DateTimeOffset dto;
if (DateTimeOffset.TryParseExact(dateTimeString, "yyyyMMdd_fff", 
                                 CultureInfo.InvariantCulture, 
                                 DateTimeStyles.AssumeUniversal |
                                 DateTimeStyles.AdjustToUniversal, out dto))

{
     Console.WriteLine(dto.ToString("yyyyMMdd"));  // prints 20181230
     Console.WriteLine(dto.ToString("fff")); // prints 183
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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