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"
Related
I'm trying to read a list of string from excel and parse it to a date.
I specified the format of the string in excel was d/M/yyyy but sometimes I got the string in the format dd/MM/yyyy, d/MM/yyyy, d/M/yyyy HH:mm:ss, dd/M/yyyy h:m:ss, ........ etc.
I don't care what the time is and I only want to get the string of date and parse it to a date. Do I need to define a huge array to contain all the combination of format of date and time before calling TryParseExact? or is there any smart way to do so?
You could Regex to rearrange the date string to M/d/y which can be parsed easily:
DateTime dt = DateTime.Parse(Regex.Replace(inputStr, #"(\d+)/(\d+)/(\d+)(.*)", #"$2/$1/$3"), CultureInfo.InvariantCulture);
Your best option is going to be to ensure that the data from excel is in the format you want, but you can split up the date string, and make a Date object from the resulting arrays:
var datePart = (excelString.Split(' '))[0];
var dateParts = datePart.Split('/');
DateTime finalDate = new DateTime(Int32.Parse(dateParts[2]), Int32.Parse(dateParts[1]), Int32.Parse(dateParts[0]));
While this will work, since it is hard-coded, it will break if the format of dd/mm/yyyy ever changes to say yyyy-mm-dd.
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 !!
My C# application have to read some date from MySQL database. Problem I have is that format of date depends on system localisation settings.
My question is if is possible that I always get date in formats yyyy-MM-dd hh:mm:ss, and yyyy-MM-dd, no matter of localisation settings.
Thank you in advance!
If you are storing the dates as true date or datetime values, your application will get the raw binary data back, and it will not be subject to localization until you create a string representation of the date values. My guess is that you are looking at the values in the debugger or using Console.WriteLine(theValue);, which will use the current locale. Always include the desired format and/or the desired culture when converting non-string values to strings.
If you are storing the dates as strings, you will always have to know exactly what format went into the database.
Assuming the dates are stored as date or datetime: just handle the values as they are, and don't convert them to strings until you need to show them to a user:
DateTime theValue = theReader.GetDateTime(fieldOrdinal);
var theValueAsText = theValue.ToString(CultureInfo.InvariantCulture);
var specificTextRepr = theValue.ToString("yyyy-MM-dd HH:mm:ss");
The theValueAsText variable will be a string representation that is not tied to a specific culture. The specificTextRepr will be your specific text representation.
You shouldn't be reading it back as a string from the database - you haven't shown how you're reading the data, but if you use something to populate a DataTable, or LINQ, or IDataReader.GetDateTime then there's no string formatting involved (assuming it's stored properly in the database, which it looks like it is).
A DateTime value doesn't intrinsically have a format, any more than an int is in decimal or hex - it's how you choose to convert it that matters, and you should almost always avoid doing that formatting unless you really need to.
Since you store the dates in date and date/time specific representations, formatting does not play into it at all (as opposed to some highly discouraged storage schemes when date/time is stored as strings, when formatting does matter, but for a wrong reason).
When you query MySQL from your C# code, you will get the correct dates no matter what your locale is. They will be displayed differently based on the locale, but they will represent the proper date regardless of the locale settings.
You can format the date directly in the query by using
date_format(dob,'%d/%m/%Y')
select date_format(dob,'%d/%m/%Y') dob from student where Id=1
Change
CurrentDate = DateTime.Now.ToString("MMM d, yyyy");
CurrentTime = DateTime.Now.ToString("hh:mm tt");
TO
CurrentDate = DateTime.Now.ToString("MMM d, yyyy",CultureInfo.InvariantCulture);
CurrentTime = DateTime.Now.ToString("hh:mm tt", CultureInfo.InvariantCulture);
I have a DateTime variable (say, timestamp) that holds a date in its usual format like this:
11/1/2011
This variable is used to build a SQL command. The Oracle database only accepts dates in the format
YYYY-MM-DD
How can I manipulate my variable to store the date in this format?
Don't format the date to include it in SQL at all.
Use a parameterized query, and then just include the value as a parameter. That way you don't have to get any formatting right at all.
You should use parameterized queries for all data - aside from formatting, it also protects you from SQL injection attacks.
Getting a date/time format which works for the particular installation of Oracle you're using right now is not the right fix. Do it properly: avoid including data in your code (the SQL).
On a different matter, your question is making incorrect assumptions to start with. A DateTime variable doesn't hold value in a "usual format" at all, any more than an int holds a decimal representation or a hex representation of a number. DateTime doesn't store text internally at all - it stores a number of ticks. How it is formatted when you call ToString depends on all kinds of cultural aspects. It's worth separating the notion of the fundamental value represented by a type from the formatted string representation you might happen to obtain by calling ToString.
I assume you send the date as string in the SQL command.
DateTime date = ...your object...;
string formattedDate = date.ToString("yyyy-MM-dd");
If it´s in string format, then you need to parse it first. It´s hard to see from your string if it´s day/month/year or month/day/year.
But you could do something like this:
string sDateTime = "11/1/2011";
DateTimeFormatInfo format = new DateTimeFormatInfo();
format.ShortDatePattern = "dd/MM/yyyy"; // or MM/dd/yyyy
DateTime date = DateTime.Parse(sDateTime, format);
string formattedDate = date.ToString("yyyy-MM-dd");
var dt = DateTime.Now;
var formatted = dt.ToString("yyyy-MM-dd");
Try this:
string oracleTimeFomatDate = DateTime.Now.ToString("yyyy-MM-dd")
I have birth dates stored as datetime in SQL Server 2008 like so:
2010-04-25 00:00:00.000
What is the best way, using C#, to convert and format this into a string with a YYYYMMDD format?
In the end, all I need is a string like:
20100425
Any help is greatly appreciated!
date.ToString("yyyyMMdd");
Should be what you need.
You need to get that value into a DateTime object and then you can use it's ToString() function like so:
.ToString("yyyyMMdd");
Are you able to get the data out of the database as a DateTime (.NET) object? If so, you can use the DateTime's instancename.ToString("yyyyMMdd")
If you haven't gotten to that stage yet, there's quite a few different ways to get the data out. It's a whole Google search in itself...
You just format the date using a custom format string:
string formatted = theDate.ToString("yyyyMMdd");
Note that the date doens't have a format at all when it's stored as a datetime in the database. It's just a point in time, it doesn't have a specific text representation until it's specifically created from the date.
Use the .ToString() method on the date time object, and pass in the format you want.