I have string value which has a format "YYYYMMDD_NNN". All are integers except _. I have to validate this string value.
validate all are Integers or not except _
The date value should not be greater than today's date.
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.