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.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:
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
DateTimevariable.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:
The
Dateproperty returns aDateTimewith 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…