Dateformat with nullable variable - c#

I have this code:
startWeekDate = startWeekDate == null ? DateTimeHelpers.calcMondayDate(DateTime.Now) : DateTimeHelpers.calcMondayDate(startWeekDate.Value);
DateTime endWeekDate = startWeekDate.Value.AddDays(6);
startWeekDate is a parameter that is nullable. This works good, but I want to format it with: String.Format("{d:0}", .... ) but when I slap that around it I get error.
Cannot implicitly convert type 'string' to 'System.DateTime?
How shall I fix this problem?
/M
EDIT:
I'm trying to add this to the function instead, since it should always return dateformat without clock, but I get same error there with this code:
public static DateTime calcMondayDate(DateTime input)
{
int delta = DayOfWeek.Monday - input.DayOfWeek;
DateTime monday = String.Format("{d:0}", input.AddDays(delta));
return monday;
}
Cannot implicitly convert type 'string' to 'System.DateTime'
hmm, but input is DateTime, why does it complain about it being string?

You've shown the code that doesn't have a problem, but not the code that does have a problem. Please show the code which doesn't compile. It sounds like you're trying to assign a DateTime? variable a string value, e.g.
startWeekDate = string.Format(...);
That's definitely not going to work. What would you really want it to do with the formatted value once you've got it as a string? Use it where you want a string, not where you want a DateTime?.
One thing to add - your first line can be expressed more simply:
startWeekDate = DateTimeHelpers.calcMondayDate(startWeekDate ?? DateTime.Now);
EDIT: Now you've posted your code, it's clear why it's not working - as suspected, you're trying to assign a string value to a DateTime variable.
DateTime values don't have a format. They're like numbers - they have a value which isn't inherently formatted. It's like 0x10 and 16 are the same number, just written differently.
Now it sounds like you're just trying to return the date without the time - which is better done as:
return input.AddDays(delta).Date;
The Date property returns a DateTime with the same date, but midnight as the time.
On a side note, it's a shame that .NET has such a restricted set of date/time types, so that you can't really represent the idea of a time-less date. I'm trying to fix this situation, but it'll be a while before it bears fruit...

The error is "cannot convert string to DateTime".
Whch is exactly what this line is attempting to do:
DateTime monday = String.Format("{d:0}", input.AddDays(delta));
As I said in my comment above, you format at output time. Internally a datetime is just a number, it has no concept of format. You should simply return the input.AddDays(delta)

You get the compilation error because you have declared startWeekDate as a DateTime, but string.Format returns a string. One possible remedy is to change the declaration:
string endWeekDate = string.Format("{d:0}", startWeekDate.Value.AddDays(6));
However, now endWeekDate is a string, so you migh want to change the code a bit to keep it as is, and then introduce a new variable which is the string representation of that variable. Whether or not that is a good idea depends on the context.

Related

Cannot convert 'string' to 'System.DateTime' C# WPF

Firstly, I want to say that I read many questions about similar problem and I couldn't find anything.
The difference is that I can't use DateTime.Now property, and I can't choose any specific date.
It is on the user to choose one date from DatePicker
I have tried Convert, Parse, tryParse, but still couldn't solve it...
This code will work fine if I use String in my class instead of DateTime, but I need to use DateTime type. Also, I don't want to display time, that's why I have formated like this. Can I get value to string, so I can parse it later?
string chosenDate = datePicker.SelectedDate.GetValueOrDefault().ToString("dd/MM/yyyy"); //error
After that I thought to move value to my object. This is what I did:
newObject = new Classes.MyClass(DateTime.Parse(chosenDate));
I have lost all ideas...
Thank you in advance.
EDIT:
Sorry for too little information about problem.
The problem is that I have a DataGrid which has binding on DateTime date (in .cs). I tried this way because it won't show time, but if I apply the following it shows the time in my result as you can see.
If MyClass expects a DateTime, you should use the value from the DatePicker's SelectedDate property. It returns a Nullable<DateTime> that can be converted to a DateTime using the GetValueOrDefault() method:
newObject = new Classes.MyClass(datePicker.SelectedDate.GetValueOrDefault());
If there is no date selected, GetValueOrDefault() will return DateTime.MinValue.
The DatePicker doesn't store the date in any particular format. That's a formatting thing.
It doesn't set the time either. If you however set the time yourself, you could strip it away using the Date property of the Date time:
datePicker.SelectedDate.GetValueOrDefault().Date

How to remove time segment completely from datetime after converting to string?

I need to pass a string parameter to a stored procedure that represents a date but is only 10 characters long. I cannot alter the stored procedure to change the variable type or length. My only option is to use C# to ensure that the parameter is suitable.
To do this I want to convert a DateTime object to a string and remove the time. I tried using the .Date method on the DateTime object but this merely converted the time to midnight. This was ok on my local machine which represented midnight by a series of zeros but on the machine I was deploying to my code midnight was represented by 12am. This causes the stored procedure to throw an exception.
I also tried forming a substring by taking the first 10 characters after converting the DateTime object to a string. However, this gave inconsistent results due to the fact that some days and months are single digits whereas others are double digit.
For example:
12/12/2010 gets converted to "12/12/2010"
but
01/01/1900 gets converted to "1/1/1900 1" (the '1' coming from the beginning of 12:00:000AM)
You can use
string date = dt.ToShortDateString();
or (synonymous)
string date = dt.ToString("d");
or
string date = dt.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
The last way ensures the format even if your current culture's date-format is different.
There are many ways to do this one to try is:
var myDateTime = DateTime.Now;
var parameter = myDateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);

Error Message as "String was not recognized as a valid DateTime."

My Code:
DateTime? birthDate = DateTime.Parse(filterDictionary.ContainsKey("DOB") ? filterDictionary["DOB"] : string.Empty);
I am getting Error Message as "String was not recognized as a valid DateTime." How to solve this issue. Thanks.
The problem (at least one of them) is that you can't parse an empty string to a DateTime.
Change your line of code to this to move the parsing only when you find the key, and return null instead of parsing when you don't have it:
DateTime? birthDate = filterDictionary.ContainsKey("DOB") ? DateTime.Parse( filterDictionary["DOB"]) : (DateTime?) null;
The other problem might be that your dictionary DOB value is actually not possible to convert to a DateTime. If the above code does not work, please edit your question and post the value in filterDictionary["DOB"] when you get this error.
Well DateTime.Parse is always going to fail when you present it with an empty string.
It's not clear whether the time that you've seen this has been one where there has been data in the dictionary but it's invalid, or whether there's been no data and it's parsing string.Empty. Also note that DateTime.Parse returns DateTime, not DateTime?. If you want the value to be null if the entry wasn't in the dictionary, I'd actually use:
DateTime? birthDate = null;
string dobText;
if (filterDictionary.TryGetValue("DOB", out dobText))
{
birthDate = DateTime.Parse(dobText);
}
Or perhaps:
string dobText;
DateTime? birthDay = filterDictionary.TryGetValue("DOB", out dobText)
? DateTime.Parse(dobText) : (DateTime?) null;
Note that you need to cast at least one of the second or third operands to null here so the compiler can work out the type of the conditional expression.
You should also consider whether a plain call to DateTime.Parse is appropriate:
If you know the specific format you're expecting, call DateTime.ParseExact
If this is user input, you should probably be using TryParse or TryParseExact
If it's not user input, you should probably be specifying a parsing culture of CultureInfo.InvariantCulture
If it's direct user input in a GUI, is there a way you can avoid getting it as text in the first place?

date from string help. I can convert to the string I want, but I can't convert back

I have a string I need to convert back to a date. I can call .ToString("yyyyMMdd") and get the string i want. My question is how can I convert that back into a date? I'm trying something like the following with no luck.
DateTime d;
var formatInfo = new DateTimeFormatInfo {ShortDatePattern = "yyyyMMdd"};
if (DateTime.TryParse(details.DetectionTime.Date, formatInfo, DateTimeStyles.None, out d))
{
lit.Text = d.ToShortTimeString(); //would like 07/30/2010 as the text
}
I've never used DateTimeFormatInfo before if that isn't obvious. Can someone point me in the right direction. I know I could probably use substring and create a new DateTime(y, m, d) etc... I'm just wondering since c# interpreted .ToString() correctly, if it can't derive a date from the very same string it output.
The reverse of DateTime.ToString("yyyyMMdd") is DateTime.TryParseExact, passing "yyyyMMdd" as a format string.
IFormatProvider is a bit of a red herring. You'll normally pass either :
Thread.CurrentThread.Culture, if you're parsing a date typed by the user, when you should obey the user's date preferences
Or CultureInfo.InvariantCulture, if you're parsing a date provided by a program, when your behaviour shouldn't depend on the preferences the user has set up
Use d.ToString("MM/dd/yyyy")
For more options check out http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx
Edit: Read it wrong
Use DateTime.Parse() to parse the string to a datetime.
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
You can also use DateTime.TryParse to see if the string is able to convert to a date first.
http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx
Alternatively you can also use Convert.ToDateTime()
If you want the DateTime variable back after sending it to a string, save yourself the trouble and just cache or pass the actual DateTime variable around scopes to wherever you need it later and don't bother converting the text back into a DateTime class..
Sorry I just realized this doesn't answer your request, so what you're looking for is:
DateTime.ParseExact(someDateTime, "the format string you used to .tostring generating the string", null);
Convert.ToDateTime("07/30/2010");
I'm assuming you mean to convert a string to a DateTime format. If so use this:
DateTime yourStringConverted = Convert.ToDateTime( yourString );

problem with conversion

This code doesn't return data from table:
var pom = from k in dataContext.student_gods
where k.skgod == System.Convert.ToString(2002/03)
select k.id_stud;
This code does return data from table:
var pom = from k in dataContext.student_gods
where k.skgod== "2002/03"
select k;
How to convert a string variable without quotes???
Taking a stab at what the OP might be running into, I suspect you have a DateTime object that you'd like to use in a query to compare against a date stored as a string. If that's the case, you can modify your query to look like:
DateTime t = ...
var pom = from k in dataContext.student_gods
where k.skgod == t.ToString("yyyy/MM")
select k;
Here, you're formatting the date to match what you're expecting to see in your database. The ToString method is formatting the date to return just the year and month components. Look to the MSDN article on Custom date and Time Format Strings for more.
To extend the example, it's currently about 3pm on Sunday, November 22nd. If I run the following code:
DateTime t = DateTime.Now();
string s = t.ToString("yyyy/MM");
Console.WriteLine(s);
...I will see 2009/11 printed.
Unlike "2002/03", 2002/03 is not a string but the integer division of 2002 by 03 (= 667).
Are you looking how to convert a DateTime to a string?
new DateTime(2002, 3, 1).ToString("yyyy/MM", CultureInfo.InvariantCulture)
This returns "2002/03".
Your problem is 2002/03 is not what you mean. What are you trying to convert here?
2002/03 is two integers and a division, and it's value is 2002 / 03 = 667. If you want the string "2002/03" you need to enter that string, "2002/03".
I hope this made sense :)
How to convert a string variable without quotes???
That doesn't make sense. String literals must be surrounded with quotes, that is what makes it a string. You cannot just try to convert undeclared variables into strings by their name, it doesn't work that way. You just need to compare against an actual string, like you do in your second example.
The string "2002/03" and 2002/03 are very different things. In C# there are no such things as string literals without quotes. C# is not PHP :-)
2002/03 is simply an integer division, namely 2002/3 = 667 (note that there are no decimal places, since this is an integer division).
So if you want to compare something with a string, then by all means use a string and not an arbitrary calculation result. Keep in mind though, that the == operator behaves somewhat erratically when applied to operands of object and string (since it might be not immediately obvious whether you are doing value or reference equality).

Categories