vb.net date formatting vs c# datetime formatting - c#

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")

Related

What is the best way to convert this date format "2019-11-07T13:30:00+05:30" to utc date?

I need a way to convert this date:
2019-11-07T13:30:00+05:30
to utc.
While also taking into account that it has +05:30
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
string dateEnd = "2019-11-07T13:30:00+05:30";
DateTime converted = Convert.ToDateTime(dateEnd);
It converts it to this date:
29-Aug-19 9:00:00 AM
dateEnd="2019-11-07T13:30:00+05:30";
matchObject.DateEnd = Convert.ToDateTime(dateEnd).ToUniversalTime();
Okay, as a warning ahead: Dealing with timezones can be madening. I try to avoid it whever I can. Luckily in .NET, we can for most cases.
Internally DateTime stores the amount of Ticks since the start of the Unix Epoch (1/1/1970). Any string and any other property you see? Those are just a interpretation of that one value.
The ToString() and Parse() functions are really good at their job. If not given another culture, they will retreive the current Culture set for windows (or their Thread). For DateTimes it will also get your local timezones to factor into the display (as nessesary).
Now the debugger is just a programm too. And it will of course display the average DateTime it is viewd from your Windows current Timezone. Or rather the timezones used by the user this programm runs in - wich can be a temporary/compilation only user with all kinds of oddities.
With the Input string the timezone of Origin is clearly noted. I can not remember having seen that Syntax, but it is propably like providing a specific port for a WebRequest. No guessing or implying of values involved. And it is accepted by Parse, so whatever :)
If you get a DateFrom a UTC related function, it will set the Kind property to UTC. Wich should fix the whole "Display in Local Timezone" thing.

want 24 hr format time in DateTime in 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.

How to handle conversion of a DateTime independently of the timezone of the hosting server?

I have an application which potentially rans in different timezones in the world, to name a few it runs in Germany & UK.
Now I have a requirement wherein I have to interpret datetime objects as they are GMT dates, and then get the equivalent UTC datetime out of it. This should happen irrespective of timezones, for example if the application is running in Germany as well the DateTime should be interpreted as GMT and converted to UTC before saving on the server.I do deal will DST shifts as well.
For ex:
If I have a datetime object like this:
var date = new Datetime(2011,03,28,01,00,00), this should be converted to it's equivalent UTC.In this case it should be 28/03/2011 01:00:00 +01:00:00, however while my server reads the saved datetime it finds it as a 28/03/2011 01:00:00 +02:00:00. My UI was running in Germany at the moment and I suspect the dates were interpreted as local dates(CET).
Can you please advise me how to perform the accurate conversion?
It's usually considered a best practice to
Store datetimes as UTC
Render this in timezone-aware user friendly format as late as possible
Thus, I would suggest you to not rely on DateTime.Now, but instead consider using DateTime.UtcNow.
Provided you allow each user to determine (through a Preferences/Options panel) to select its own timezone, then you could render an UTC date in the appropriate user-friendly format using:
string timeZoneInfoId = "Romance Standard Time"; // Or any valid Windows timezone id ;-)
var tzi = TimeZoneInfo.FindSystemTimeZoneById(timeZoneInfoId);
//Build a DateTimeOffset which holds the correct offset considering the user's timezone
var dto = new DateTimeOffset(TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, timeZoneInfo), timeZoneInfo.GetUtcOffset(utcDateTime));
var formated = string.Format("{0} {1} ({2})", dto.ToString("d"), dto.ToString("T"), dto.ToString("zzz")); //Or whatever format that fits you
Note: You can find the list of all valid Windows timeZoneId here.
Provided you're willing to add a selecting list for the user to choose its rendering timezone, you could use TimeZoneInfo.GetSystemTimeZones() to retrieve a list of TimeZoneInfo, then use the Id property of each TimeZoneInfo as the option's value and call the ToString() method of each TimeZoneInfo to render the option's content.
Your selecting list would render in a similar way than native Windows one:
For the first part of your query , you can get the UTC time from the DateTime object.
DateTime dt = DateTime.Now;
dt.ToUniversalTime().ToString() will give you UTC time.
Now incase you want to represent the same as local time, you will need to get the offset from the client end via javascript. Something like
var now = new Date();
var offset = now.getTimezoneOffset();
Now you may use this offset to display the Time for the client by adding or subtracting the minutes you get from this method.
Hope this helps.
Take a look at the TimeZoneInfo class: http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx
date += TimeZone.CurrentTimeZone.GetUtcOffset(date);

How to specify a 12-hour time format in SQL Server 2008

I am using SQL Server 2008 and I have a database file (mydata.mdf) in which I have a column in one of the table and that column has the datatype (Time) .
I added this database file to my WPF-C# project (using VS2010) , but I had a problem and its as follows :
This (Time) column treats time in 24-Hours system , but I want to use (12-Hour) system in my application , so is there a way to define a 12-Hour system time in SQL server2008 .
and if there isn't , what do you think is the best way to handle that ???
Pleeeeeeeeeeease help me ASAP because I'm in a hurry and I can't figure it out ...
The time in the database is not "formatted". It is represented in some internal format (which you can Google for but shouldn't care about) that allows it to represent each moment in the day, to the supported level of precision.
The values are only formatted when your application converts them to strings for the purpose of displaying them to the user, and you have full control over this.
So if you have read a time into an instance of the CLR DateTime class, you can display as a 12-hour time (omitting the date) with value.ToString("h:mm:ss tt"). Custom formatting options are listed here.
The answer is you can't really, but don't worry, it's not a problem. Format the date in your C# code.
The point is that a date and time is an absolute value, which is what you want SQL to store, then 12 hour vs 24 hour clock is merely a display detail, eg, 13:00 and 1:00pm are equivalent, don't worry about how SQL stores it, then in C# use the following to display it:
DateTime myDateTime = GetTheTimeFromSomeMethod();
myDateTime.ToString("h:mm:ss tt");
There are lots of guides, This is a good one, but there are plenty of others eg this one
Does it have to be formatted from the database? C# and WPF both provide many built-in date format options. For example, check out the ContentStringFormat property on a Label.
If you must do it in the database, here is a messy workaround which will work
It formats the date as a string using a 12h clock, then removes the date part of it
select right(convert(varchar, cast('1/1/2010 23:59:59' as datetime), 100),
charindex(' ', reverse(convert(varchar, cast('1/1/2010 23:59:59' as datetime), 100)))-1)

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