i have the following object that can be nullable at times follows
public string issued {get;set;}
The issued
string looks like this: 2022/02/29 22:00:00 00:00
I want to assign the issued variable to another variable as 2022/02/29
when its not null.
This is what i tried:
var item = new model() {
issuedDate=issued.IsNullOrEmpty() ? "" : issued.ToString("yyyy/mm/dd")
}
But it throws an error:
can not convert from string to system.IformatProvider?
How can I fix this?
CodePudding user response:
I recommend using DateTime
as helper with TryParseExact
to determine if the source is a valid DateTime
format. Via the DateTime
helper variable you can then create any DateTime
formatted strings you need to.
string issued = @"2022/02/29 22:00:00 00:00";
string issuedDate;
DateTime dateTimeIssued;
if (DateTime.TryParseExact(issued, "yyyy/MM/dd HH:mm:ss zzz", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTimeIssued)) {
issuedDate = dateTimeIssued.ToString("yyyy/MM/dd");
}
Be aware that TryParseExact
only works if the format is known to the system culture.
CodePudding user response:
you can try for format;
string.Format("{0:yyyy/MM/dd}",issued);
this will be return 2022/02/29 for you
and you can look this page, for more information on DateTime format.