Convert DateTime to string with format YYYYMMDD - c#

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.

Related

C#, datetime.parse Error 32510 can not parse

everyone.
I have a datetime coming back from a music file in the format:
32510
Maybe, it means 1989/01/02
How can i get the datetime.parse function to pick up on this? Ie parse it without erroring? Cheers
This DateTime(32510) is in double so we can't simply use datetime.parse to convert 32510 to DateTime. To convert a double to date we need to use DateTime.FromOADate method.
For more details you can go through this MSDN link:
https://msdn.microsoft.com/en-us/library/system.datetime.fromoadate(v=vs.110).aspx
Quite often interop dates are stored as integers, so you'll need to convert them to actual dates. See below as an example:
var dt = DateTime.FromOADate(32510);
Console.WriteLine(dt);
Where the output is:
2/01/1989 12:00:00 AM
I don't think you can use DateTime.Parse() to convert 32510 to 1989/01/02 though.
It sounds me like Ole Date, try using DateTime.FromOADate
DateTime date = DateTime.FromOADate(32510)
//output - 1/2/1989 12:00:00 AM

Date type in MySql

I'm new to MySQL and C#.
I stored certain values in a column with data type Date. I did not want the time, only the date to be stored.
On viewing these values using phpMyAdmin or MySql command line, I see them in the format:
YYYY-MM-DD
However, when I retrieve these values in to my web application, they are displayed in the following format:
YYYY-MM-DD HH:MM (the time is specifically 12:00).
Why does this happen? And how can I prevent this from happening?
when you store in C# your date field, you use DateTime object. In this object when you don't specify the time part will be put a default value depends on Globalization.
You can study how DateTime works here
You can convert the date to the format you like when you fetch the data, using date_format():
select date_format(datecol, '%Y-%m-%d')
This returns the value as a string.
You shouldn't retrieve the value as a string from mysql. Why? Because if you ever need to do any operations on that value, such as adding a day, then you will need to parse it back into a DateTime again. String parsing can be slow, and when it comes to dates they are prone to errors like misinterpretation of mm/dd/yyyy and dd/mm/yyyy formatting.
The problem you have is that .NET does not have just a Date type. It only has a DateTime type. So loading a MySQL DATE type, is going to get a DateTime with the time portion set to midnight.
There's no direct problem with that, except on how are outputting the result. If you just call .ToString() without any parameters, or you implicitly use it as a string, then you are going to get a result with the full date and time. You simply need to provide a parameter to indicate what formatting you want.
Without any parameters, you are getting the General "G" format. This is explained in the documentation here.
In other words:
yourDateTime.ToString() == yourDateTime.ToString("G")
You can read about all of the other formats available, here and here.
In particular, if you just want the date, then you probably want to do this:
yourDateTime.ToString("d")
Based on your comments, you should be doing this instead:
MySQL Query:
SELECT Gbstartdate FROM TblGbDef
C#:
DateTime gb_start_date = (DateTime) datareader[0];

SQL datetime to C# string and back to SQL datetime

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"

Changing DATETIME format in datatable column without using loop in C#

I have a Data Table that has a column 'subscribeDate' that has dates in MM/dd/yyyy hh:mm:ss format. I would like to change all the dates in this column to MM-dd-yyyy hh:mm:ss format. Is there a way that I can do it without running a loop?
I would hope that the values in the DataTable are of type DateTime or DateTimeOffset.
Assuming that's the case, they don't have a format. They're just dates and times. How you convert them to a string is up to you.
If they're not already in an appropriate data type, you should try to change how you obtain the data to start with. Convert it from a string format to a more appropriate data type as early as you possibly can, and only convert it back to a string when you really need to.
You haven't explained how you're displaying the DataTable, but most ways that I'm aware of allow you to specify a format string - that's where you would specify your MM-dd-yyyy HH:mm:ss format. (Note HH rather than hh, to get 24 hours.)
You should be able to do that, if there is not some culture restrictions in your app (I don't know how works your application) with convert method.
Somethign like this:
myTable.Columns["Date"].Convert(
val => DateTime.Parse(val.ToString()).ToString("dd/MMM/yyyy"));
Where convert function you can find in Is it possible to format a date column of a datatable?

convert date to string

I'm getting data from a stored procedure and wonder which is the easiest way to convert DateTime (or date) to string?
recipes.Add(new Recipe
{
RecipeId = reader.GetInt32(recipeIdIndex),
Name = reader.GetString(nameIndex),
Date = reader.GetDateTime(dateIndex), //Date is a string
});
Assuming reader.GetDateTime() is returning a c# DateTime object, all you need to do is call ToString() on it passing in arguments to format it how you like.
reader.GetDateTime(dateIndex).ToString("yyyy-MM-dd HH:mm:ss.ttt")
The best way to convert date to string is not do it at all.
If you have to store date time as strings use DateTime.ToString("o") or ISO8601 format .ToString("yyyy-MM-dd HH:mm:ss.ttt") as SynXsiS suggested.
Make sure you know if date is in local or UTC time - you may need to adjust values before displaying to a user.

Categories