C# DateTime and String value condition check - c#

I have a problem.
This is not working
> var from = "";
> StartDTime = Convert.ToDateTime(from);
This is working
> var from = "2021-10-05";
> StartDTime = Convert.ToDateTime(from);
Some time I'm sending Date Value, but sometime in not sending Date Value.in that time from variable pass as a empty string. I want to set if from variable is = "" then need to set default Date Value.so how can I resolve this?. Please help me guys. Thank you

A safe way of doing that would be:
StartDTime = string.IsNullOrEmpty(from) ? DateTime.Now : DateTime.Parse(from);
But if you have control over the code passing the "from" variable, you can declare it as nullable DateTime, then your code would look like this:
DateTime? from = null;
var StartDTime = from.HasValue ? from.Value : DateTime.Now;
Which for short would be:
StartDTime = from ?? DateTime.Now;

DateTime.TryParse will do the job for you:
for example:
DateTime dateTime;
var from = "";
DateTime.TryParse(from, out dateTime);

One-liner, with only the validation you specify:
StartDTime = from == "" ? new DateTime() : Convert.ToDateTime(from);

It's not ellegant, but works.
var from = "";
if(from == ""){ from = DateTime.MinValue.ToString(); }
DateTime StartDTime = Convert.ToDateTime(from);
But i think that a nullable DateTime would be more elegant, like this:
var from = null;
DateTime? StartDTime = from;
Or you can set a default date, like this:
var from = null;
DateTime? StartDTime = from ?? YourDefaultDate;

Convert methods either successfully convert the string passed to it, or throws an error, that's the way it's supposed to work. For most data types there are also TryParse methods that return true/false based on if it converted successfully and have an output variable which will be DateTime.MinValue if it failed. This is how I would handle your situation:
DateTime startDTime;
string from = "";
if (!DateTime.TryParse(from, out startDTime)){
startDTime = DateTime.Now;
}
This will set the startTime to the date passed in from, but if no date was passed it sets it to the current date and time - if you want a different default value, that replaces new DateTime() and if your default should be January 1, 0001, then you can just use the TryParse part directly, since that's the automatic default for a failed TryParse.

Related

Csharp Swapping Dynamic values in string

I want to swap two values in a STRING
This is an example of doing it with characters:
string str = "PQRQP";
var res= str.Select(a=> a == 'P' ? 'Q' : (a=='Q' ? 'P' : a)).ToArray();
str = new String(res);
Console.WriteLine(str);
But my string is 2/7/2019, where i want to swap the 2 and 7 each time but as these values are from user input i wont know what they will be before runtime.
Any help appreciated, thanks in advance !
-----------MY SOLUTION----------------
String values = DateRangePicker1.Value.ToString();
String startDate = values.Substring(0, 8);
String endDate = values.Substring(11, 8);
DateTime date = DateTime.ParseExact(startDate, "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime date1 = DateTime.ParseExact(endDate, "M/d/yyyy", CultureInfo.InvariantCulture);
String newSDate = date.ToString();
String newEDate = date1.ToString();
String finalSDate = newSDate.Substring(0, 10);
String finalEDate = newEDate.Substring(0, 10);
I know this is slightly messy, but is working for me without affecting performance
This rather seems to be a localization issue (based on the fact that you are providing a string that looks like a date)
Is it possible that by just providing the correct date annotation that this would solve your problem?
DateTime.ParseExact(string)
for instance is a method that allows you to create a datetime object from a string, if you tell it what the string format is
example:
DateTime date = DateTime.ParseExact("2/1/2019", "M/d/yyyy", CultureInfo.InvariantCulture);
will provide a datetime object set to the first of febuary 2019. You can then convert the datetime object to a string with:
date.ToString("dd-MM-yy");
output: 01-02-19
Edit: if you have a range of acceptable formats, it is possible to provide an array of formats in string form.
You can use split to get the charachters you dont know.
Like this:
var sepratedInput = input.split('/');
var res= sepratedInput[1] +"/"+sepratedInput[0]+"/"+sepratedInput[2];
Console.write(res);

Trouble with setting values in a class to .Empty

I'm creating a program that uses Microsoft access and i'm having trouble with setting a value in a class to .Empty. It works fine with a string but it does not work with int or DateTime, i'm wondering what could I use instead?
public CustomerData()
{
FirstName = string.Empty;
LastName = string.Empty;
Company = string.Empty;
Question1 = string.Empty;
Question2 = string.Empty;
Question3 = string.Empty;
Question4 = string.Empty;
Question5 = int.Empty;
FeedbackComments = string.Empty;
FDate = DateTime.Empty;
}
There is no Empty property for DateTime class, probably you should use MinValue; property to initialize the date time variable. which will initialize the variable with 1/1/0001 12:00:00 AM. So the code for this would be
FDate = DateTime.MinValue;
Read more about DateTime.MinValue, Same in the case of int.Empty, you can use 0 instead or int.MinValue which will give you -2147483648
A DateTime object is of different type from a String object and there isn't any implicit conversion between them. Hence, you can't assign a String value to a variable that can hold DateTime values. I would say that you have two otpions
Use the DateTime.MinValue, FDate = DateTime.MinValue.
Redeclare the type of value as DateTime? and set the value of null.

Use of unassigned local variable 'strCity'

this is the error its giving, my biz code is fine as well as stored procedure, without "strCity" variable everything was working fine, but the moment i added this addition, is causing me trouble
txtCityName.Text = null;
string strVal = hdnOption.Value;
IFormatProvider provider = new System.Globalization.CultureInfo("en-GB", true);
DateTime dtStart = new DateTime();
DateTime? dtEnd = null;
string strCity;
if (strVal == "today")
{
HideCustomSearch();
dtStart = DateTime.Today;
dtEnd = DateTime.Today;
strCity = txtCityName.Text.ToString().Trim();
}
if (strVal == "weekly")
{
HideCustomSearch();
dtStart = DateTime.Now.AddDays(-7).Date;
dtEnd = DateTime.Today;
strCity = txtCityName.Text.ToString().Trim();
}
if (strVal == "byweekly")
{
HideCustomSearch();
dtStart = DateTime.Now.AddDays(-15).Date;
dtEnd = DateTime.Today;
strCity = txtCityName.Text.ToString().Trim();
}
if (strVal == "monthly")
{
HideCustomSearch();
dtStart = DateTime.Now.AddMonths(-1).Date;
dtEnd = DateTime.Today;
strCity = txtCityName.Text.ToString().Trim();
}
if (strVal == "yearly")
{
HideCustomSearch();
dtStart = DateTime.Now.AddYears(-1).Date;
dtEnd = DateTime.Today;
strCity = txtCityName.Text.ToString().Trim();
}
if (strVal == "custom")
{
ShowCustomSearch();
dtStart = DateTime.Now;
dtEnd = DateTime.Now;
strCity = txtCityName.Text.ToString().Trim();
strCity = null;
hdndtStart.Value = txtdtStart.ToString();
hdndtEnd.Value = txtdtEnd.Text.ToString();
}
FillGridFilter(dtStart, dtEnd, strCity);
P.S. its giving me error on last line "strCity" only
Your error occures because you have not got an 'else' anywhere after the ifs. The compiler can not verify that the value 'strCity' will ever be assigned (there might be a number of different options for 'strVal ').
You therefor have to assign a default value.
Writing the code as a switch statement:
http://msdn.microsoft.com/en-us/library/vstudio/06tc147t.aspx
would probable make it more clear since you can define a 'default' case in those situations.
Better still, assign null to strCity, use else if instead of if in your conditional logic and test for strCity being null before your call to FillGridFilter.
From what I can see all the possible options for your strVal variable are mutually exclusive so there is no need to force re-evaluation of it in each test.
You have to assign some default value to local variables.
This error is given in your case because compiler is thinking string strCity; may never get assigned value.
While declaring string strCity; assign some value to it.
string strCity="";
or
string strCity=string.Empty;
Try this, error will go.
Because you have used if staments with lot of conditions. The value will be assigned at runtime to the strCity variable.But after the if statement the strCity you have used as parameter to the function FillGridFilter so the compiler will not sure the if condition is exicutes or not. that's way
Error
Use of unassigned local variable 'strCity'
it's showing
so better to assign the default value to the variable strCity
Better to put
string strCity=null;
or
string strCity=String.Empty;
But make sure that FillGridFilter function handles the null or empty value.
Regards,
Nitin Joshi

String was not recognized as a valid DateTime

I want to add a date in session (date1) like this:
Session["DateLesson"] = date1.ToString("dd.MM.yyyy");
Now from the session I want take this value:
var asd = Session["DateLesson"];
/*asd = "20.04.2012"*/
var datelesson = DateTime.Parse((string) asd);
And it gives me this exception:
FormatException not recognized as a valid DateTime
A period is not a valid/standard separator character in most locales. You'll need to use DateTime.ParseExact() in combination with a format string to tell the function how to read it. More importantly, if reading it back to a datetime is your main goal, why not just put the datetime in the session as is? That seems way more efficient, easier, and more maintainable to me.
Why persist your date as a string?
You could simply store it like this:
Session["DateLesson"] = date1;
And then retrieve it like this:
var datelesson = (DateTime)Session["DateLesson"];
string value = "20.04.2012";
DateTime datetime = DateTime.ParseExact(value, "dd.MM.yyyy", null);
This will return 4/20/2012 12:00:00:00 AM
Don't keep value as a string but as an object of the initial type:
public DateTime? DateLesson
{
get
{
DateTime? dateTime = Session["DateLesson"] as DateTime?;
if (dateTime.HasValue) // not null
{
// use dateTime.Value
}
}
set
{
Session["DateLesson"] = value;
}
}

Retrieving a DateTime value from a DataRow (C#)

How can I get DateTime value in C# from row, the current code is giving me error
any help is appreciated, the data is coming in from progress database:
foreach (DataRow r in ds.Tables[0].Rows)
{
string prodCode = r["PRD-CDE"].ToString();
statCode = r["STAT"].ToString();
DateTime firstIssueDate = (DateTime)(r["FISS"]);
DateTime endIssueDate = (DateTime)(r["EISS"]);
if(endIssueDate > DateTime.Now)
{ /*do some thing...*/}
else {/*user invalid...*/}
}
there are two ways used in getting date convert and pars, thank you all for the help
Final working Code snippet:
foreach (DataRow r in ds.Tables[0].Rows)
{
string prodCode = r["PRD-CDE"].ToString(),statCode = r["STAT"].ToString();
// r.<DateTime?>("FISS");
if (r["FISS"] != DBNull.Value)
{
DateTime firstIssueDate = Convert.ToDateTime(r["FISS"]);
if (r["EISS"] != DBNull.Value)
{
DateTime endIssueDate = DateTime.Parse(r["EISS"].ToString());
if (endIssueDate > DateTime.Now)
{
This is just a guess but if the corresponding type in the database is DateTime, could you check if the column is nullable?
If so you may want to do a check r["column"] == DBNull.Value and then pass it to a nullable DateTime? Field.
Or even easier:
row.Field<DateTime?>("column")
If it isn't then yeah, Convert.ToDateTime() or something else should do it.
EDIT:
I see your final code there but is there any chance you want to do this:
DateTime? firstIssueDate = r.Field<DateTime?>("fiss");
DateTime? endIssueDate = r.Field<DateTime?>("eiss");
if (firstIssueDate.HasValue && endIssueDate.HasValue)
{
firstIssueDate.Value // blah blah
endIssueDate.Value // blah blah
}
I would recommend using DateTime.Parse() if the row is returning a string for that index.
string prodCode = r["PRD-CDE"].ToString(),statCode = r["STAT"].ToString();
DateTime firstIssueDate = DateTime.Parse(r["FISS"].ToString());
DateTime endIssueDate = DateTime.Parse(r["EISS"].ToString());
You could also use TryParse depending on your needs.
If you want to use a default value (such as DateTime.MinValue), rather than null (DateTime?) or DBNull, you could do this:
var firstIssueDate = r["FISS"] as DateTime? ?? DateTime.MinValue;
var endIssueDate = r["EISS"] as DateTime? ?? DateTime.MinValue;
foreach (DataRow r in ds.Tables[0].Rows)
{
string prodCode = r["PRD-CDE"].ToString();
string statCode = r["STAT"].ToString();
DateTime firstIssueDate = DateTime.Parse((r["FISS"]).ToString());
DateTime endIssueDate = DateTime.Parse((r["EISS"]).ToString());
if(endIssueDate > DateTime.Now)
{ /*do some thing...*/}
else {/*user invalid...*/}
}
This should compile and may work for you. Though it is certainly not performing any error checking that you should do for production code. Also look into DateTime.TryParse and you may to look into adding a IFormatProvider to ensure the format is parsed as expected.
First of all, do r["FISS"].GetType() and print it to console (or pause and look at it in the debugger). If it says it's a String, then most of the above advices will help. If it says something else, please come back and update your question.
As a side answer, you could use also the static function Convert.ToDateTime
DateTime.Parse(r["FISS"].ToString()) is the way to go, but it throws a "String was not recognized as a valid DateTime" error. Could you show the actual string in the r["FISS"] column, it might be a internationalisation problem....
If you have a DateTime string with a special format (not any standard .NET DateTime format) that needs to be converted to .NET DateTime type, you can use DateTime.ParseExact() method.
Please see the MSDN document for more details including examples.
If you have multiple formats to parse, try DateTime.ParseExact Method (String, String[], IFormatProvider, DateTimeStyles)

Categories