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
Related
I was trying to validate a date read from app.config file using DateTime.TryParse() method. However, it returned true when the input was "12/05/201". This was actually a typo, and should have been, "12/05/2018". When I stepped through the code it automatically converted the date to "12/05/0201" and returned true. However when I used DateTime.TryParseExact(), it correctly returned false for the above input. So, should we always use DateTime.TryParseExact()? I am little confused because earlier I used use DateTime.TryParse() whenever I had to validate a date string! Both the code is given below:
Boolean isValidStartDate = DateTime.TryParse(startDate, out DateTime startDateVerified);
CultureInfo enUS = new CultureInfo("en-US");
Boolean isValidStartDate = DateTime.TryParseExact(startDate,"MM/dd/yyyy",enUS, DateTimeStyles.None, out DateTime startDateVerified);
Thanks
The year 201 being invalid is business logic - if you want to have logical safeguards on your imported data (and you should), do them explicitly. With C# you can easily add an extension method to DateTime if you want, something like
public static DateTime ParseDateWithSanity(this DateTime, string date)
{
dt = DateTime.Parse(date);
if dt.Year < 1900
{
throw BadInputException()
}
}
Best way to Validate date depends upon the use case and input data source and its formate
DateTime.TryParse is parsed using formatting information in the current DateTimeFormatInfo object so let's say if you use TryParse "12/05/201" it will return the parsed data according to your current culture settings. Which is "12/05/0201" ie in date format "MM/DD/YYYY"
Its always good practice to specify date formate and culture variance while parsing date and use TryParseExact instead of TryParse
(Note: To know about current culture settings you can look for a member of classes CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture)
Unlike the U.S.A ... most other countries uses the dd/MM/yyyy format (from smallest to biggest). However, .NET naturally takes in date in MM/dd/yyyy format.
I have an input that accepts a datetime, and the user will want to type in the date in dd/MM/yyyy format, let's say they type in 30/1/2017 ... but when that date is posted in the backend, it becomes unrecognized.. or it becomes reversed (1/2/2017 becomes 2/1/2017).
[HttpPost]
public ActionResult Save(DateTime date) // user entered 1/2/2017 from front-end
{
date.ToString("dd/MM/yyyy"); // this becomes 2/1/2017
}
Is there some kind of global setting to reverse this recognization of date in .NET? I would not like to manually switch dates from front-end because that seems like alot of work and alot of places to do it from.
You'd be better off setting the culture on the thread or in the controller initialization, or in the routing. There are a couple of answers in this question that show several excellent ways to do it.
The point is, the Thread.CurrentCulture controls the formatting of date/time and currency, among other cool things...so you can focus on the real solution, and leave all the trivial work to the framework.
DateTime.ParseExact is one of the shots you can try.
You need to specify culture, and then parse the date:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime.ParseExact("01/02/2017", "dd/MM/yyyy", provider);
DateTime.ParseExact("01/02/2017", "MM/dd/yyyy", provider);
If you will show output, the first one will be [01.02.2017 00:00:00] and the seccond [02.01.2017 00:00:00]
Your solution does not work, because when you are getting the data, it's probalbly get with the same American format of "MM/dd/yyyy"
DateTime isn't a good idea for serialisation/deserialisation like that because of stuff like this, or timezones. Rather than trying to hack it such that it works, avoid it altogether by sending it as a Unix timestamp (or similar things, like strings with timezone info that you then parse), and then turn it into a DateTime on your end.
You can follow this answer and cater it to your purposes like so:
[HttpPost]
public ActionResult Save(double timestamp)
{
var date = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc).AddSeconds( timestamp );
}
This isn't ideal, but there must be a way to automate it. Be aware your front-end will need to send it as a normal Unix timestamp (Javascript, for example, uses a timestamp in milliseconds instead of seconds.) and as UTC. This also avoids timezone issues.
If you will going to use this format conversion multiple times, why not to use a Helper Method ?
Like this c# console aplication exemple:
static void Main(string[] args)
{
DateTime mydate = new DateTime(2017, 04, 08);
string myValue = convertDate(mydate);
Console.WriteLine(myValue);
Console.ReadKey();
}
private static string convertDate(DateTime dateToConvert)
{
return string.Format("{0:MM/dd/yyyy}", dateToConvert);
}
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"
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")