Converting string to DateTime safely - c#

I have a string that came from a Database, but I´m not sure that will be a valid dateTime.
First I´m trying to validate if it´s null,
then if not null I want to safely convert it to DateTime because I´m not sure that a row["a"].ToString will be a valid DateTime
output.limitExpiryDate = row["a"] == DBNull.Value ? DateTime.Now : "something to convert here";
Does anyone have any idea?

You can use DateTime.TryParse:
output.limitExpiryDate = DateTime.Now;
DateTime limitExpiryDate;
if(row["a"] != DBNull.Value && DateTime.TryParse(row.Field<string>("a"), out limitExpiryDate))
output.limitExpiryDate = limitExpiryDate;
It it was a nullable DateTime column you could use the Field method that supports nullable types:
DateTime? limitExpiryDate = row.Field<DateTime?>("a");
if(limitExpiryDate.HasValue)
output.limitExpiryDate = limitExpiryDate.Value;

CultureInfo provider = CultureInfo.InvariantCulture;
var format = "yyyy-MM-dd";
output.limitExpiryDate = row["a"] == DBNull.Value ? DateTime.Now : DateTime.ParseExact(row["a"], format, provider);

Something like this:
DateTime date = DateTime.Now;
if (row["a"] != null && row["a"] != DBNull.Value)
{
if (!DateTime.TryParse(row["a"], out date))
date = DateTime.Now;
}
output.limitExpiryDate = date;
or you can use TryParseExact and specify format, if you know what datetime format your row["a"] has.

You can use this. It doesnt give any problem for any date format. It works for me.
public static DateTime? ToDateTime(this string value)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
return Convert.ToDateTime(value);
}

Related

Convert string to DateTime using special format

How can I convert this string to a DateTime:
string t = "2017-02-20 13h24m18s";
The format is: XXXX-XX-XX XXhXXmXXs
You could use DateTime.TryParseExact to parse the string using a specific format:
string t = "2017-02-20 13h24m18s";
if(DateTime.TryParseExact(t, #"yyyy-MM-dd HH\hmm\mss\s", CultureInfo.InvariantCulture,
DateTimeStyles.None, out var dt))
{
// parsed successfully into dt
}
Just be sure to escape 13h as HH\h, 24m as mm\m and 18s as ss\s.
You can replace values easily before converting
static public DateTime todate(string t)
{
t = t.Replace("h", ":");
t = t.Replace("m", ":");
t = t.Replace("s", "");
return DateTime.Parse(t);
}
now use
string test = "2017-02-20 13h2m18s";
DateTime a = todate(test);

Convert dd/mm/yyyy string to yyyy-dd-mm DateTime in c#

How do I convert 13/05/2019 (dd/mm/yyyy) string to 2019-13-05 (YYYY-dd-mm) DateTime Datatype in c#,sql sever Expects YYYY-dd-mm format datatype
string dateTime = "05/13/2019";
if (animalAdoption.AdoptionId != 0)
{
AnimalsAndBirdsAdoption animalsAndBirdsAdoption = new AnimalsAndBirdsAdoption()
{
AnimalsAndBirdsId = animalAdoption.AnimalId,
DonarDetailsId = userId,
Term = model.Term,
PeriodOfAdoption = dateTime,
isActive = true,
Amount = animalAdoption.amount
};
if (context.AnimalsAndBirdsAdoptions.Any(e => e.Id == animalAdoption.AdoptionId))
{
context.AnimalsAndBirdsAdoptions.Attach(animalsAndBirdsAdoption);
}
else
{
context.AnimalsAndBirdsAdoptions.Add(animalsAndBirdsAdoption);
}
}
this out-put I get
You can do it simply using below example with using your required format:
string dateTime = "05/13/2019";
CultureInfo provider = CultureInfo.InvariantCulture;
// It throws Argument null exception
DateTime dateTime10 = DateTime.ParseExact(dateTime, "yyyy/dd/mm", provider);
string dateTime = "13/05/2019";
var splittedDateTime = dateTime.Split('/');
DateTime myDate = new DateTime(int.Parse(splittedDateTime[2]), int.Parse(splittedDateTime[1]), int.Parse(splittedDateTime[0]));
To convert a UK date string to a DateTime
public DateTime? ToDateTime(string text)
{
DateTime? returnValue = null;
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-GB");
DateTime d = new DateTime();
if(DateTime.TryParse(text, cultureInfo, System.Globalization.DateTimeStyles.None, out d))
{
returnValue = d;
}
return returnValue;
}
To convert a DateTime to string yyyy-MM-dd:
public string ToBigEndianString(DateTime? date)
{
string returnValue = null;
if(date != null)
{
returnValue = date.Value.ToString("yyyy-MM-dd");
}
return returnValue;
}
Then you can put them together:
public string ToBigEndianString(string ukDate)
{
DateTime? d = ToDateTime(ukDate);
return ToBigEndianString(d);
}
But you could pass in a DateTime to a SQL stored procedure.
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparametercollection.addwithvalue?view=netframework-4.8
Change the datatype of PeriodOfAdoption to Type System.DateTime
and then you can initialise the property using the DateTime constructor which has many overloads.
If your string format is always in the form yyyy-dd-mm based on: '2019-13-05'
you can extract the year the month and the day, by perhaps using .Split('-') string function or if its the format: '2019/13/05' you can split on '/' e.g. .Split('/').
Then you can create your DateTime object using the constructor like so (you can view them here https://learn.microsoft.com/en-us/dotnet/api/system.datetime.-ctor?view=netframework-4.8):
constructor:
public DateTime (int year, int month, int day);
initialisation:
PeriodOfAdoption = new DateTime(2019, 5, 13)
so putting it together:
var dateTime = '2019/13/05';
var dateParts = dateTime.Split('/');
PeriodOfAdoption = new DateTime(Int32.parse(dateParts[0]), Int32.parse(dateParts[1]), Int32.parse(dateParts[2]));
If you need a string in the c# side, this is very simple in C# and there are many examples online

How to convert a date value from sql server with c#?

I'm using WinForms and C#, and I'm trying to compare between a date from the database and the current date.
My code is the following :
DataManager.NotificationManager obj = new DataManager.NotificationManager();
DataTable dt1 = obj.GetListExpiryDate();
string currendate = DateTime.Today.ToString("yyyy-MM-dd");
foreach (DataRow row in dt1.Rows)
{
if (DateTime.Parse(row.ItemArray[41].ToString("dd/MM/yyyy")) == currendate)
{
MessageBox.Show("Expired carte for the employee" + row["EmpFName"]);
} //.RowStyles[0].Height = 0; this.tlp_id.ColumnStyles[1].Width = 0; }
else
{
MessageBox.Show(" not Expired carte for the employee" + row["EmpFName"]);
}
}
The problem is that the data coming from the database doesn't have the same format of the currentdate value!
Any ideas please?
Do not format the date coming from the database as a string. Instead, use the value as DateTime:
if (((DateTime)row.ItemArray[41]).Date == DateTime.Today) {
MessageBox.Show("Expired carte for the employee" + row["EmpFName"]);
}
This way formatting would become irrelevant.
Note the use of .Date and DateTime.Today to ensure that only the date portion would be compared, ignoring the time portion.
Instead of converting the DateTime to a string in currentdate, convert the return from the database to a DateTime value and compare those.
DataManager.NotificationManager obj = new DataManager.NotificationManager();
DataTable dt1 = obj.GetListExpiryDate();
DateTime currendate = DateTime.Today;
foreach(DataRow row in dt1.Rows)
{
if (DateTime.Parse(row.ItemArray[41].ToString().Date) == currendate)
{
MessageBox.Show("Expired carte for the employee" + row["EmpFName"]);
}
else
{
MessageBox.Show(" not Expired carte for the employee"+row["EmpFName"]);
}
}
If Item 41 is indeed a DateTime object, the simplest thing to do would be:
var dt = row[41] as DateTime;
if (dt != null) {
// process dt as a DateTime object.
}
While using DateTime conversions, I would suggest one to use the TryParse();It allows you to provide an array of strings as your possible input formats.
Here's the most overloaded signature:
public static DateTime ParseExact(
string s,
string[] formats,
IFormatProvider provider,
DateTimeStyles style
)

Convert string to DateTime Format - wrong format

I really cannot make sense of why this does not want to work. I get an exception:
String was not recognized as a valid DateTime.
I am reading the string date from a file and looks like this 2/27/2014 10:10:55
This method receives the filename and extrapolates the data I need (latitude, longitude, date)
public void ReadCsvFile(string filename)
{
var reader = new StreamReader(File.OpenRead(filename));
gpsDataList = new List<GpsFileClass>();
while(!reader.EndOfStream){
var line = reader.ReadLine();
var values = line.Split(',');
if(values[2].Contains("A")){
values[2] = values[2].Substring(0,values[2].IndexOf("A"));
values[2].Replace("\"", "");
values[2] = values[2].Trim();
}
if(values[2].Contains("P")){
values[2] = values[2].Substring(0, values[2].IndexOf("P"));
values[2].Replace("\"", "");
values[2] = values[2].Trim();
}
gpsDataList.Add(new GpsFileClass(Convert.ToDouble(values[0]), Convert.ToDouble(values[1]), Convert.ToString(values[2])));
}
}
Once the I have the file data in a List<> I want to do some date comparisons and calculations. But first; I try to convert the string data containing date information to datetime like this:
public void SaveFrameGpsCoordinate()
{
int listSize = gpsDataList.Count;
DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();
dateTimeFormatInfo.ShortDatePattern = "dd-MM-yyyy HH:mm:ss";
dateTimeFormatInfo.DateSeparator = "/";
//DateTime tempDateA = DateTime.ParseExact(gpsDataList[0].timeCaptured, "dd/MM/yyyy HH:mm:ss",null);
//DateTime tempDateB = DateTime.ParseExact(gpsDataList[lastRecordData].timeCaptured, "dd/MM/yyyy HH:mm:ss", null);
DateTime tempDateA = Convert.ToDateTime(gpsDataList[0].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
DateTime tempDateB = Convert.ToDateTime(gpsDataList[lastRecordData].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
}
As you can see even ParseExact throws the same exception, I tried it (hence commented it out).
There are a lot solutions for this kind of problem but non seem to work on mine. I get that DateTime by default uses en-US calture. But When I even when I change the culture to "af-ZA" I get the same exception.
Please help.
I don't believe it; The variable that holds the size of the List<> was going out of range (check line 3 of code below) but for some reason it did not throw an "out of range exception".
public void SaveFrameGpsCoordinate()
{
int listSize = gpsDataList.Count - 1;
DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();
dateTimeFormatInfo.ShortDatePattern = "dd-MM-yyyy HH:mm:ss";
dateTimeFormatInfo.DateSeparator = "/";
//DateTime tempDateA = DateTime.ParseExact(gpsDataList[0].timeCaptured, "dd/MM/yyyy HH:mm:ss",null);
//DateTime tempDateB = DateTime.ParseExact(gpsDataList[lastRecordData].timeCaptured, "dd/MM/yyyy HH:mm:ss", null);
DateTime tempDateA = Convert.ToDateTime(gpsDataList[0].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
DateTime tempDateB = Convert.ToDateTime(gpsDataList[lastRecordData].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
}
You can use the ParseExact method
var dateTime = DateTime.ParseExact("2/27/2014 10:10:55",
"M/d/yyyy h:m:s", CultureInfo.InvariantCulture);
'dd' expects a 2 digit date. You probably want to use 'd' instead.
Similarly 'MM' expects a 2 digit month - again you probably want to use 'M' instead.
Source: http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

DateTime TryParse problem

string date = txtWorkingDate.Text;
DateTime dateTime = DateTime.MinValue;
if (DateTime.TryParse(date, out dateTime))
{
args.IsValid = true;
}
else
args.IsValid = false;
txtWorkingDate.Text is like "dd.MM.yyyy" becouse of this validateion is always false if date is not like "dd.MM.yyyy". How c an i check types of date like "dd.MM.yyyy", "MM/dd/yyyy" becouse are all valid.
By using this overload and providing the accepted formats:
string date = txtWorkingDate.Text;
DateTime dateTime;
string[] formats = new[] { "dd.MM.yyyy", "MM/dd/yyyy" };
if (DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
System.Globalization.CultureInfo cultureinfo =
new System.Globalization.CultureInfo("en-gb");
DateTime dt = DateTime.Parse("13/12/2009", cultureinfo);
You need to specify the culture assuming you know it.
You can use the
DateTime.TryParse(
string s,
IFormatProvider provider,
DateTimeStyles styles,
out DateTime result
)
overload.
Also, you don't need the if, you can simply write
args.IsValid = DateTime.TryParse(...);
As DateTime.TryParse() already returns a bool.

Categories