want 24 hr format time in DateTime in C# - c#

My date and time are stored in database in 24 hr format.What i do is use a stored procedure to fetch the required date and times and insert in a datatable. But in the datatable it automatically converts in 12 hr format.After fetching data from datatable it is possible to convert it into 24hr pattern but it has to be converted into string.But the problem is that i need to use the data to create a chart which would only accept DateTime format.
So what i want is some way to convert 12 hr time to 24 hr time format without changing it to string.Please help.

My date and time are stored in database in 24 hr format.
I hope they're not actually stored in any text format, but instead in a DateTime field or something similar. Don't confuse "what I see when I run a SQL query" with "what's stored in the database." Just as numbers aren't stored as sequences of decimal digits, dates and times shouldn't be stored as text.
But in the datatable it automatically converts in 12 hr format.
No, if you've done everything properly it should be storing everything in the DataTable as a DateTime. In the debugger you may see a 12-hour string representation, but the object itself should be a DateTime.
Basically the 12/24-hour problem is only a symptom of the real problem: unnecessary string conversions. Track those down (and remove them), and the rest should take care of itself. So if yo're currently calling ToString() when you extract the value from the DataTable, stop doing that. Instead, just cast:
DateTime dateTime = (DateTime) row["foo"];

From your story, I understand that the DataTable actually contains a DateTime value, which doesn't have any format by itself, it basically just stores a number of ticks since an arbitrary date and time. What you are seeing in your table visualization is the default ToString() conversion, based on your application's culture settings.
Most likely, if you were to do something like this before running your existing code, the format would change:
var cultureInfo = new CultureInfo(CultureInfo.CurrentCulture.Name);
cultureInfo.DateTimeFormat.LongTimePattern = "HH:mm:ss";
Thread.CurrentThread.CurrentCulture = cultureInfo;
I would recommend converting to a format of your preference by calling ToString explictly however. How exactly you would best accomplish this depends on how you are visualizing the data from the DataTable.

All that #Jon said is right.
But if you just explained yourself wrong, and you do have DateTime object in your db, and you are looking to format it into 24 hr only when displaying - you can use "HH" in string format for 24 hour format.
For example, for myDateTime representing 16:00:
var hourPart = String.Format("{0:HH}", myDateTime)
Console.WriteLine(hourPart); // prints 16, and not 4PM.

Related

vb.net date formatting vs c# datetime formatting

I am doing an Visual Studio vb.net WinForm App.
I am used to work with c#. In C# Datetime DataType I have configured as "dd/MM/yyyy" as is configured in Control Panel and Regedit.
In VB.Net, is different, when I create a Date variable like this
Dim var As New Date
var = DateTime.Now
Date.Now returns format "mm/dd/yyyy".
So every date format a assign to a variable, VB.Net automatically convert to format "mm/dd/yyyy".
I need Date DataType in VB.Net to be configured as C#. I mean, "dd/MM/yyyy" as it is configured in Control Panel.
Is that possible?
Thanks
I want to work in format dd/MM/yyyy
Actually, you don't. You want to work with dates as DateTime types, because it's most flexible. Storing and working with dates as another type (such as a string in a particular format) in inherently less flexible and more error prone than using the proper type.
This is a perceptual problem; you think about dates in a certain way, and you seem to be demanding the computer represent them in YOUR way, but that's the flaw; you need to work with dates in the way .net does it because it's the best way.
In the same way that you wouldn't think of storing/working your numbers in a string, because "2" + "2" = "22", whereas 2 + 2 = 4, you should store, manipulate and process dates are DateTimes. If you want a particular representation just as the date data is being displayed on screen, THEN you can format it into MM/dd/yy for your american friends, or dd-MM-yyyy for your Europeans
dd= 16 +'/'+ 10 +'/'+ 17
It should assign 16/10/2017, but it assign 10/16/2017..
Other people have covered this, but whatever class that Date is, dump it, and use a built in DateTime, maybe like this:
DateTime d = new DateTime(2017, 10, 16);
DateTime has a constructor that takes a year, month and day. Once you have your datetime object you can manipulate it with the AddXXX methods to add 10 days or subtract 15 hours etc. You can do onedate - anotherdate and get a TimeSpan object that will tell you how many minutes, hours, etc are between the two dates.. And so on
But it need it to define in General to all application. I need that Date type defined as dd/MM/yyyy by default.
You can't. .NET will never think of your date in any way other than the way it does internally, it will never process it in any way other than it's programmed to do. You say you know how to format it on the way out to a report.. and you seem to be saying you want to specify that format globally so that every time you, or anyone looks at a date, it's that format. You must appreciate that .net will still treat dates as the way it does internally. You can and should only influence the part of the process that puts the date on screen in some visible form for the user to read.. But really, if you're writing an application that will be used by other people, you shouldn't override the way their system treats dates, within your app..
You should instead just work with dates as dates, .ToString() them onto screen when you need to and let the thread, that is dealing with the conversion, use whatever culture specific settings it picked up from the user's operating system. This way your app uses dates as dates, and the american using your app sees 10/12/2017 and knows it's the 12th oct, and the european using your app sees 12-10-2017 and knows the same
If you want to force a particular date format during development, set your windows culture settings to the formatting you want. Don't hard code a date format into your app
If I ask for DateTime.Now ,it returns a "MM/dd/yyyy", I need to retrieve a format "dd/MM/YYYY"
No, it doesn't. Datetime.Now returns you a DateTime object of a snapshot of the computer's clock at the time it was called. It represents the date internally as a number, not a string, not in any format etc. When you MessageBox.Show it (or whatever) it's converted to a string text representation and that's what you're seeing as "MM/dd/yyyy" but sure as heck DateTime.Now is not returning you a string like "10/12/2017"
In Main() I add
Dim dd As DateTime = DateTime.Now
Soo.. Just run me through the logic of the part where you tagged this question as C#, said it was C# and just now you've dumped a load of VB.NET from "your program" into it?
I want a global setting so I get "dd/MM/YYYY" in all my Application, so I do not need to Parse or Cast every time I need it....
Really, think on what I've said about how .NET treats dates. You stores dates as DateTime instances. When you get user input and create user output, those are really the only times you might need to convert from a string representation to a date, but on the input side of things there are controls such as DatePicker that allow the user to choose a date and time, and give you the value they chose, as a DateTime - no strings involved. On the output side; leave it - let the dates display in whatever format the user (including you) has picked in his Windows Region control panel
If you're reading in a text file with dates in a certain format, that's when you'd use DateTime.ParseExact(), to convert that text representation, into a DAteTime.. But you store it in your app memory, in xml files, in database columns etc, as a proper DateTime (or equivalent) datatype, NOT a string
The problem here is not with how .NET thinks about dates, it's with how you're thinking about them/how you think .net thinks about them. Once you're over that part, it'll get much easier
Override the date format on Global.asax
protected void Application_BeginRequest(Object sender, EventArgs e)
{
CultureInfo newCulture = (CultureInfo) System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
newCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
newCulture.DateTimeFormat.DateSeparator = "/";
Thread.CurrentThread.CurrentCulture = newCulture;
}
In C#,
string date_string = dd.ToString("dd-MM-yyyy");
In VB.Net
Dim date_string As String = dd.ToString("dd-MM-yyyy")

Data which shows up as a date in 'mm/dd/YYYY' format on spreadsheet appears as number in C#

I've loaded data from a delimited .doc file into an Excel workbook application using a querytable.
Subsequently I'm trying to loop through the data on the worksheet and save the data into particular variable types e.g.:
string gender = range.Rows.Cells[index + 7].FormulaLocal;
DateTime birth_date =Convert.ToDateTime(range.Rows.Cells[index + 8].FormulaLocal);
int SSN = Convert.ToInt32(range.Rows.Cells[index + 9].FormulaLocal);
I get an exception, however with the above code saying
"String was not recognized as a valid DateTime."
Now on screen in the worksheet the data in that field reads "07/09/1972"
However in the debugger I'm instead getting a value of "26489" and this seems to be the source of the exception as c# cannot convert this into a DateTime Object.
Anyone know what's going on here and how best to fix it?
When converting from Office, you must use the DateTime.FromOADate method. This is because Office uses OLE Automation date, which is a format where a floating point value is calculated, counting the days from the last of December 1899. The hours and minutes are represented as fractional days, thus adding a few decimals to the value 26489 would result in a time stamp that also represents hours, minutes and seconds.
DateTime d = DateTime.FromOADate(26489);
Console.WriteLine(d);
will output
1972-07-09 00:00:00
Excel stores dates as numbers (representing number of days and fractional days since midnight, 30 December 1899) - use FromOADate to convert to a CLR DataTime
double dbl = range.Value;
DAteTime dt = DateTime.FromOADate(dbl);
DateTime.FromOADate(Convert.ToDouble(text)).ToString("MM/dd/yyyy")

How I can convert DateTime.now in C# to yyyy-mm-dd hh:mm:ss.sssssss?

I'm storing in my database using a store procedure the date time stamp using a function called sysdatetime() and a type of varchar(max) which stores in the database in this format yyyy-mm-dd hh:mm:ss.sssssss. When I'm creating a new post its fine but when I'm trying to update the record I have to send a parameter to the store procedure with the current datetime. I have tried this one
DateTime.Now.ToString(yyyy-mm-dd hh:mm:ss.sssssss)
but I'm getting an error. what i have to do?
P.s: see the image below with the error message
I suspect if you really need the string representation, you actually want:
string text = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fffffff",
CultureInfo.InvariantCulture)
Note that:
Unless you really want the local time, use UtcNow instead of Now. For timestamps, you almost always want UTC.
I doubt that you want to use the time separator of the current culture, hence the specification of CultureInfo.InvariantCulture
"MM" means months whereas "mm" means minutes
"HH" means 24-hour clock whereas "hh" means 12-hour clock
"ff..." is used for fractions of a second
See MSDN for more details of custom date and time formatting.
However, I'd strongly recommend that you try to avoid string conversions wherever possible. Why can't your stored procedure just use the relevant DateTime type instead of a string representation? Then you can pass the value to the stored procedure as a DateTime (via a command parameter) and you can get rid of the error-prone string conversion clutter.
Use this code:
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffff")
See this ref: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Here a small sample:
DateTime date3 = new DateTime(2008, 1, 1, 0, 30, 45, 125);
Console.WriteLine("Date with milliseconds: {0:MM/dd/yyy hh:mm:ss.fff}",
date3);
// Displays the following output to the console:
// Date with milliseconds: 01/01/2008 12:30:45.125
Just put the appropriate number of "f"s into your command and you are done

how to add current date time in bigint field

I need to add the current date time in a bigint field in a database... and then display from that only the date in format: october 1, 2009.
I am currently thinking of storing the value in string variable and then converting it to int...
String s = DateTime.Now.ToString();
i dont know what to do next..
please help
You could just store the number of ticks as your bigint value. Ticks represent the number of elapsed 1/10,000 of milliseconds since January 1, 0001.
DateTime.Now.Ticks;
This can always be converted back to a DateTime by using the constructor that accepts a long:
DateTime storedTime = new DateTime(ticksFromDatabase);
To format your date, just use any of the standard date format strings. A custom format string might work better actually, I just perused them and it doesn't look like there's a built in one for the format you want. This should work:
date1.ToString("MMMM d, yyyy", CultureInfo.CreateSpecificCulture("en-US"))
I'd use a smart date key, since it's easier to find that using SQL:
20090927235000
yyyyMMddhhmmss
This way, if you want to find anything that happened on a given day, you could do:
select * from tbl where datecol between 20090927000000 and 20090927240000
Thereby making data validation a lot easier, even if you are using an ORM.

Incomplete DateTime In C#

In C# if I want to parse a datetime, but some times I just have either a date and not a time component or no date but a time component, how would I do this? Usually when you leave out the time component, it automatically assumes that the time is 12:00AM. But I don't want this. If the time component is missing then I just want the DateTime to store a date only and the leave the time component off.
The value of a DateTime internally is just an UInt64 (ulong in C#) that stores the number of ticks since some date in the past, so whether you like it or not, the time component will always be there.
If you only need to display certain parts, just use any of the format strings (examples are for "en-us" culture):
DateTime.Now.ToString("d"); // 5/26/2009
DateTime.Now.ToString("t"); // 4:56 PM
The complete reference: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
It's not possible to have a DateTime without a time component. You could store a boolean flag along with it in a struct to store data about existence of that component. However, there's no way to use the automatic parsing routine to distinguish between a DateTime string with a time specified as 12:00 PM and a nonexistent one.
If it really bugs you you can always create a wrapper class that can hide the time portions of the datetime class.
No you will have the time component no matter what. The best you can do is access the Date property on your DateTime object if you really have to.
http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx
DateTime by definition stores a date and a time such that it cannot just represent one of them without representing the other. If you only want the date (or only the time), parse out the information you need and discard the rest of it.
As mentioned before DateTime will always have a Date and a Time part of it if you only want a single part use the way described by the others
DateTime date = DateTime.Parse("2009-11-30);
date.Year; = 2009
date.Month; = 11
date.Day; = 30
date.Hour; = 0
and so on
The thing you must be aware is that all of these methods will only return an integer.
If you want to know all the possible ways to parse a string John Sheehan has put together a great Cheat Sheet wit all possible ways to parse and manipulate dates, and other strings for that matter.
You could have a class that stores a DateTime and determines if the time was ever set or if just the date was set and return values accordingly.
Use
DateTime date = new DateTime();
date = DateTime.Parse("1/1/2001");
to set the date, then use
date.ToShortDateString();
or
date.Year;
date.Month;
date.Day;
to get what you need. Hope that helps!
A DateTime object is always stores a date + a time, not just one. You can always choose to work only with the date part, i.e. only use properties like Year, Month, DayOfWeek. But underneath there will aways be some stored time.
It is very dangerous to assume that the date portion of a DateTime is necessarily the date you are expecting. As pointed-out, DateTime always includes and considers the time aspect, even when you don't see it.
This is a big problem when you have data stored in different time-zones (and particularly if knowledge of that offset is not also kept, because it is assumed that what is being stored is a Date, not a date-with-time).
You may store a birthdate as '01/01/2000 00:00:00' during Summer-Time, which then is stored in UCT as '31/12/1999 23:00:00'. When you then read that birth-date later, the date portion is now a day early.
Best to create your own type. Strange that Microsoft didn't think it worth having a Date type.

Categories