I want to insert the DateTime.Now as dd-MMM-yyyy format, but it is giving me string is not recognized as valid datetime while I use ParseExact.
db.AddInParameter(objdbCommand, "#dtAddedOn", DbType.DateTime, DateTime.ParseExact(Convert.ToString(DateTime.Now), #"dd-MMM-yyyy", System.Globalization.CultureInfo.InvariantCulture));
I have also tried :
DateTime.ParseExact(Convert.ToString(DateTime.Now), #"dd-MMM-yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture));
but it is giving me the same error
Since you are inserting a DateTime anyway, you do not need to Convert to string and parse back to DateTime.
db.AddInParameter(objdbCommand, "#dtAddedOn", DbType.DateTime, DateTime.Now);
will do the trick.
DateTime does not have a format. Format comes into play as soon as you need a textual representation of the value that the DateTime represents. I also wouldn't recommend to use Convert for this but one of DateTime.ToString overloads.
Edit:
If you do not want to include the Time part, i.e. insert the Date, only you can use DateTime.Now.Date (see Date Property) or even easier DateTime.Today. This will give you a DateTime object with Time components all set to zero.
Edit 2:
Mind that there are some inherent problems using DateTime, especially if your system is going to be used spanning different TimeZones. Going deeper into this would go beyond the scope of this answer, though. Just want to give you a heads-up.
You may want to checkout DateTimeOffset and related Articles like Choosing between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo
Related
I've two types of dates, one in DateTime format and another in string format, both dates having the following format:
yyyy-MM-dd HH: mm: ss
I want to delete HH: mm: ss because I need to compare these dates in a loop to iterate through a database. The problem's that one of these dates is returned by a CalendarSelectionDate event, and the hour, minutes and seconds are even set to 0. Anyone have the best way to do this?
UPDATE:
if (DateTime.TryParseExact(reader["data"].ToString(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt)){...}
The code behavior return an invalid date, in particular if I've 12/05/15 ... the code will return 1/01/0001
If you want to compare DateTime objects without the hour, you can use the Date property:
if (myDbDate.Date != myUserDate.Date) { }
You can also cast the date to a string using ToString(), but be aware that dates are a notoriously very hard thing to deal with when they are strings:
if (myDbDate.ToShortDateString() != myUserDate) { }
or if you are very sure of your format, you can use a custom date format:
if (myDbDate.ToString("yyyy-MM-dd") != myUserDate) { }
Update
Automatically parsing the string to a date (with DateTime.Parse or TryParse) has often resulted, in my own and personal experience, in very random results. You never seem to know which format .Net will decide on using (dd/MM or MM/dd ?).
Using ParseExact or TryParseExact solves this problem, and allows to work on the date further (add days, for instance). But for a simple comparison as in the initial question, since you're "locking" the date format in the code, it doesn't change much (maybe performance-wise, I don't know), and it's much more simple to cast the date to a string than the other way.
That being said, I went on the assumption that the comparison was "is different". If the comparison is "is later/earlier than", casting to a date would indeed be the right solution.
First you have to understand that DateTime does not have a format. It only contains information that describes a specific point in time. Formats apply to the string representations of a DateTime. For what you want you can use DateTime.Date which will return a new DateTime with the same year, month, and day values, but with the time set to 12 AM. That along with DateTime.ParseExact will allow you to parse the string to a DateTime then compare just the Date part.
var someDate = DateTime.ParseExact(stringValue, "yyyy-MM-dd HH: mm: ss");
if(someDate.Date != otherDate.Date)
{
}
To get the base date of any DateTime, simply use the Date property.
DateTime.Now.Date
I have a DataTable coming from a stored procedure which I'm writing to an excel file. There's a column with a DateTime datatype, and looking at the values in there, they're just generic dates with the time stamp.
I've tried using the DateTime.Date property, but that still gives me a time stamp. Further, I've tried to create a new DateTime object using the year,month,day constructor but it still adds a time stamp:
DateTime newDate = DateTime(oldDate.Year, oldDate.Month, oldDate.Day);
I'm trying to keep the column datatype to DateTime but remove the time stamp, so this rules out ToString("") formatting. Is there another way?
A DateTime always contains a date and a time portion. If you use the Date property it returns a new DateTime where the time is 0:00:00 so midnight at the same day. You want a string representation of the datetime without the time.
You can use DateTime.ToString:
string result = oldDate.ToString("d"); // uses current culture's date format
or
string result = oldDate.ToShortDateString(); // same as above
or
string result = oldDate.ToString("MM-dd-yyyy"); // custom format
Edit: "so this rules out ToString("") formatting. Is there another way?"
No, because of the reason mentioned above.
It's important to separate the data from how it is displayed. If you need to display it without time use the code above, you can store the original DateTime variable for future processing, select it again from database or use DateTime.Parse/DateTime.ParseExcact to get a DateTime from the string.
The 'problem' is that there is no Date struct in .NET, you only have a DateTime struct. That will always contain both date and time. You can only format it as date.
Or, you could of course write your own struct containing only the date part, or give up and use string.Format to format it as a date (possibly using the short date string d).
If you mean time part with timestamp, a DateTime instance always have both date and time part. DateTime.Date property just sets the time value set to midnight.
You can get it's string representation if you want only it's Date part. You can get standard date and time format or custom date and time format with DateTime.ToString() method.
Usually, you can use ShortDatePattern to get only string representation of Date part which uses standard "d" format of your CurrentCulture.
DateTime.Now.ToString("d");
There is a proposal for System.Date and System.Time types for .NET Framework in dotnet/corefx on GitHub page by the way.
Proposal: System.Date type
You should use DateTime.Now.ToShortDateString();
I have a webservice method that gets data from sql of the format
2012-11-18 11:21:03 when i save it to C# string it becomes this format: 18.11.2012 11:21:03
How do i change it back to the SQL format 2012-11-18 11:21:03 ?
Parse it into a dateTime again
DateTime myTime = DateTime.Parse(myString);
and back into a proper to string
myTime.ToString("yyyy-MM-dd HH:mm:ss");
Or just read it into a datetime and cut out the middleman.
You can get the universally sortable string format (which looks like the one used by SQL server) by using the format string "u" like this:
var dateTimeString = String.Format("{0:u}", yourDateTime);
Simply run the below code,
var newDateTime = oldDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");
Its just converting it back to the SQL Format DATETIME
Trouble with Dates as strings is they are ambiguous and the formats can vary based on where you are in the world, or even local machine settings. You might assume a date string is yyyy-mm-dd but what if it is actually yyyy-dd-mm? Some dates will appear to work and some will be invalid.
In other words is 2013-02-10 the 10th of February or is it the 2nd of October? If it is just a string you have no way of knowing for sure what was intended.
Your best bet as suggested by #Haedrian is to store in a DateTime C# object, not a string. That way it is never ambiguous and you have access to various date specific functions. If you must store as a string you can convert back to a date as above or use
DateTime.TryParse(datestring, out dateVariable);
which won't throw an exception for an invalid format. Depends if you want exceptions!
Also I would suggest if you must use strings to use a 3 character month in strings, which again eliminates the ambiguity, e.g.
"dd-MMM-yy hh:mm tt"
I have date string in format dd-MMM-yyyy and want to convert this to datetime, when I use below code
DateTime.ParseExact("20-Oct-2012", "yyyy-MM-dd HH:mm tt", null)
it causing an error
String was not recognized as a valid DateTime.
When I modify above code
DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null)
then I got date time in format (mm/dd/yyyy) : 10/20/2012 12:00:00 AM
But I need it should be converted in yyyy/mm/dd format. Please help me in this regard.
You should try this
DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null).ToString("yyyy/mm/dd")
For further reading on formats Check This
You need to distinguish between two separate concerns: that of parsing your original string into an abstract DateTime representation, and that of converting the latter back into another string representation.
In your code, you're only tackling the former, and relying on the implicit ToString() method call (which uses the system's current locale) to convert it back to string. If you want to control the output format, you need to specify it explicitly:
// Convert from string in "dd-MMM-yyyy" format to DateTime.
DateTime dt = DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null);
// Convert from DateTime to string in "yyyy/MM/dd" format.
string str = dt.ToString("yyyy/MM/dd");
Also note that the mm format specifier represents minutes; months are represented by MM.
Edit: 'Converted date contain value "10/20/2012 12:00:00 AM".' Be careful what you mean by that. The constructed DateTime value contains an abstract representation of the parsed date and time that is independent of any format.
However, in order to display it, you need to convert it back into some string representation. When you view the variable in the debugger (as you're presumably doing), Visual Studio automatically calls the parameterless ToString() method on the DateTime, which renders the date and time under the current culture (which, in your case, assumes the US culture).
To alter this behaviour such that it renders the date and time under a custom format, you need to explicitly call the ToString(string) overload (or one of the other overloads), as I've shown in the example above.
You could try this instead :
Convert.ToDateTime("20-Oct-2012").ToString("yyyy/MM/dd")
Hope this will help !!
I'm trying to store a shortened date (mm/dd/yyyy) into a DateTime object. The following code below is what I am currently trying to do; this includes the time (12:00:00 AM) which I do not want :(
DateTime goodDateHolder = Convert.ToDateTime(DateTime.Now.ToShortDateString());
Result will be 10/19/2009 12:00:00 AM
DateTime is an integer interpreted to represent both parts of DateTime (ie: date and time). You will always have both date and time in DateTime. Sorry, there's nothing you can do about it.
You can use .Date to get the date part. In these cases, the time will always be 12:00 but you can just ignore that part if you don't want it.
You only have two options in this situation.
1) Ignore the time part of the value.
2) Create a wrapper class.
Personally, I am inclined to use option 1.
A DateTime will always have a time component - even if it is 12:00:00 AM. You just need to format the DateTime when you display it (e.g. goodDateHolder.ToShortDateString()).
Instead of .Now you can use .Today which will not remove the time part, but will only fill the date part and leave time to the default value.
Later on, as others pointed out, you should try to get the date part ignoring the time part, depending on the situation.
You'll always get the time portion in a DateTime type.
DateTime goodDateHolder = Convert.ToDateTime(DateTime.Now.ToShortDateString());
will give you today's date but will always show the time to be midnight.
If you're worried about formatting then you would try something like this
goodDateHolder.ToString("mm/dd/yyyy")
to get the date in the format that you want.
This is a good resource msdn-dateformat
You can also check out Noda Time based off the Java Joda Time library.
DateTime object stores both the date and the time. To display only the date, you would use the DateTime.ToString(string) method.
DateTime goodDateHolder = DateTime.Now;
// outputs 10/19/2009
Console.WriteLine(goodDateHolder.ToString("MM/dd/yyyy"));
For more information on the ToString method, follow this link
You might not be able to get it as a DateTime object...but when you want to display it you can format it in the way you want by doing something like.
myDateTime.ToString("M/d/yyyy") which gives 10/19/2009 for your example.
DateTime is merely a UInt64 with useful and clever formatting wrapped around it to make it appear like a date plus a time. You cannot eliminate the time element.