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")
Related
There is an input from CSV file which is in dd/mm/yyyy format.
I have to pass these date values to the stored procedure.
I want to convert this to mm/dd/yyyy format before I bulkcopy it to the database table from the datatable in the c# code.
Should I do this in the code or in the stored procedure which I am sending it to?
Please advise.I have tried all possible combinations.
You could you use DateTime.ParseExact,
var parsedDate = DateTime.ParseExact(dateString, "dd/MM/YYYY", CultureInfo.InvariantCulture);
where dateString is the string representation of the date you want to parse.
If your stored procedures expects a DateTime you could use the parseDate value. Otherwise, if it expects a string in the format you mentioned, you can pass the following value:
parsedDate.ToString("MM/dd/YYYY")
You should parse your value to DateTime in C# and pass this date value to your SQL client or ORM without converting it to a string
If your SQL column type is set to either one of the date value types it is quite impossible to format the date according to your desire, since the database engine does not store the formatted value but the date value itself.
Make sure to parse the DateTime in-code before updating its value in the SQL database.
string date = "2000-02-02";
DateTime time = DateTime.Parse(date); // Will throw an exception if the date is invalid.
There's also the TryParse method available for you. It will make sure the date value you're trying to parse is indeed in the right format.
string input = "2000-02-02";
DateTime dateTime;
if (DateTime.TryParse(input, out dateTime))
{
Console.WriteLine(dateTime);
}
After the storage you're more than welcome to select your preferred display format for your DateTime variable using one of the given formats (read link below for a full list of available formats).
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
I have a date that is entered through the system (from a database) as dd/mm/yy I need to programmatically convert the date to en-US format to mm/dd/yyyy so that I can do some date calculations within the code. The code that I have so far is:
String myJames = "25/04/13" // Date String comes in as non-US date
String myJames2 = System.DateTime.Today.ToString(myJames); // I think the problem is here
DateTime d1 = Convert.ToDateTime(myJames2);
DateTime d2 = DateTime.Now;
TimeSpan t = d2 - d1;
double NrOfDays = t.TotalDays;
I know this is not completely correct, especially in the first few lines. Any help getting the dates into one en-US format for effective comparisons would be greatly appreciated.
Just to check I understand your question. You have a date as a string and you want to convert that string into a datetime so you can use it in a calculation? And your problem is that the string isn't in the format that the locale the code is running in would use?
In which case use DateTime.ParseExact.
DateTime d1 = DateTime.ParseExact(myJames,"dd/MM/yy");
This line of code would replace your line declaring and assigning d1. The line assigning to myJames2 can be removed as it isn't needed.
Everytime you convert from or to a string, culturesettings are involved.
So.. if you are converting a DateTime to string, and your culture is en-US, it will automatically converted to: MM/dd/YYYY.
This is also true for converting back. If you convert a string back to a DateTime, the culturesettings are used to see what format the string is in.
Teh culture settings are always: Thread.CurrentThread.CurrentCulture.
Most conversion functions allow to override the format (like "MM/dd/yyyy") and/or the culture. So you can create your own culture and use this during conversions.
You say the database uses dd/MM/yy, but normaly a DateTime in a database is not formatted, it is just a binary value. Or is it stored as a text? If it is stored as a text, than you should ALWAYS convert it to a DateTime using the correct culture or format.
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 the following code -
DateTime timeStamp;
timeStamp = System.Convert.ToDateTime(y.InnerText);
Where y.InnerText is 11/03/2013 11:35:24.
However this is breaking my import statement as it the database is looking for the format -
2013-03-11 11:35:24
How can I set the format of the DateTime object?
How can I set the format of the DateTime object?
You can't. DateTime values don't have formats, any more than int or double values do. When you want to convert them to/from strings, that's where you specify any formatting information.
Instead, you should use parameterized SQL and avoid converting the DateTime value back into a string in the first place. This is a general best practice - don't include values in your SQL string; parameterized SQL has multiple benefits:
It avoids SQL injection attacks
It avoids conversion issues like this one
It keeps your code (SQL) separate from your data (parameter values)
I would also suggest that instead of using Convert.ToDateTime, you specify your expected format when parsing. For example:
timeStamp = DateTime.ParseExact(y.InnerText,
"dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Basically, the two rules I try to apply are:
Avoid performing any conversions where you don't have to. If you make sure that every system uses the right data types as far as possible, you often don't need to make any conversions at all.
Where you do need to convert to/from string representations, be very explicit about the representation you want to consume/produce. For machine-readable values, that should usually use the invariant culture and possibly a custom date/time format. For human-readable values, that should usually use the user's culture and a standard date/time format.
I use this step
Convert to DateTime.
Use ToString(); function
Example :
DateTime myDateTime = DateTime.Now;
string myDateTimeString = myDateTime.ToString("yyyy-MM-dd hh:mm:ss");
if you are passing datetime to sql database try with yourdatetime.ToString("yyyy/MM/dd") format this will work for you.
and one more thing you can add a datetime format for your Applicaton culture. so this will treat you datetime format at you desire.
using System;
using System.Globalization;
using System.Threading;
namespace test {
public static class Program {
public static void Main() {
CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = "yyyy/MM/dd HH:mm:ss";
culture.DateTimeFormat.LongTimePattern = "";
Thread.CurrentThread.CurrentCulture = culture;
Console.WriteLine(DateTime.Now);
}
}
}
Basically Date does not have a format. If the database parameter/field is Datetime type you should be fine passing as a Date type. It is not a good idea to pass date as a string.
However, if that something you have to deal with, then you better pass the Date in a none culture specific date format (ISO8601 or ISO) in a parameterised query. Otherwise you could have problems with database servers in different culture settings.
For example, for sql server, it is safe (in conversion) to pass date time in ISO8601 as;
'yyyy-mm-ddThh:mi:ss.mmm' //(no spaces)
you can use ToString convertion to 2013-03-11 11:35:24
DateTime timeStamp;
timeStamp = System.Convert.ToDateTime(y.InnerText).ToString("yyyy-MM-dd HH:mm:ss");
And what if you just override your ToString() method of your DateTime object?
Wouldn't you be able then to choose the format you want and every time it is used, it will be formatted in the way you want it without being bothered by it.
This is just a thought so I don't know if there are better solutions or not.
You can then use the properties year, month, day, to build it like you want.
Something like:
public override ToString(){
return this.Year + "-" + this.Month + "-" + this.Day;
}
Greetings
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);