Format Date and Time in .NET - c#

How to format date and time to local system date and time format? I need to format date and time separately. Suppose date is "06/11/2013" and time is "16:00:00" now both need to be formatted to system current date format and time format (with am/pm if 12 hours mode).

DateTime.ToString() takes a string format parameter that allows you to create whatever format you want. http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
If you use DateTime.Now to get the current date/time of the server you can then use the .ToString() method to format your output.

using System.Globalization;
string date = DateTime.Now.ToString("MM-dd-yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);

Related

Format date using DateTime.ToString() based on TimeZone

I read the following question Creating a DateTime in a specific Time Zone in c# and was able to create a DateTime with TimeZone information. But I need to convert the DateTime to string value based on TimeZone.
E.g. I've set the TimeZone as India Standard Time and created a DateTime, when I tried to convert to string using ToString() instead of 13/12/2019 4:00:00 PM, I am getting 12/13/2019 4:00:00 PM. Since I've set the TimeZone as India Standard Time, I would like to display the date in India Format (dd/mm/yyyy) rather than mm/dd/yyyy.
So, how do I format the date based on TimeZone in C#?
Edit: I completely understand that Format and Timezone are different things. But I need to format the DateTime to match user's geography which I can identify using his timezone provided as input.
If you only want a string representation of the DateTime that matches a specific culture you can use the DateTime.ToString(IFormatProvider) overload to specify the target culture you want to use. The date will be formatted accordingly. If you want to format your date and time you want to do this based on the culture of the user and not based on the timezone. People in Kongo and Germany share the same timezone but are formatting their date and time differently.
var myDate = DateTime.Now();
var myDateString = myDate.ToString(new CultureInfo("fr-FR"));
would print the date and time in a french format for example.
You can also format your DateTime with a custom format:
var myDate = DateTime.Now;
var myDateString = myDate.ToString("dd/MM/yyyy hh:mm");
References:
- DateTime.ToString(IFormatProvider)
- DateTime.ToString(string)
- CultureInfo
- Date and time formatting

Can not Parse string to DateTime in Windows Phone 7

I am trying to convert the string to DateTime. But I can not convert.
DateTime dt = DateTime.Parse("16/11/2014", CultureInfo.InvariantCulture);
Console.WriteLine("Date==> " + dt);
The error is FormatException.
My input time format is "dd/MM/yyyy".
Please let me any idea to resolve my problem.
Given that you know your input format, you should specify it with `ParseExact:
DateTime dt = DateTime.ParseExact(text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
I would always recommend being as explicit as you can be about date/time formats. It makes your intention very clear, and avoids the possibility of getting months and days the wrong way round.
As Soner has stated, CultureInfo.InvariantCulture uses MM/dd/yyyy as its short date pattern, as you can validate with:
Console.WriteLine(CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern)
As a mild plug, you might want to consider using my Noda Time project for your date/time handling - aside from anything else, that allows you to treat a date as a date, rather than as a date and time...
Because InvariantCulture doesn't have dd/MM/yyyy as a standard date and time format, but it has MM/dd/yyyy as a standard date and time format.
That's why it thinks your string is MM/dd/yyyy format, but since there is no 16 as a month in Gregorian calender, you get FormatException.
Instead of that, you can use DateTime.TryParseExact method to specify exact format like;
string s = "16/11/2014";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
}

Convert HH:MM:ss string into datetime

I am reading from excel file and save the content into database
one of the column contains length of video in this format
HH:mm:ss
I write this code so far
string time = oledbReader[6].ToString();
DateTime streamingTime = DateTime.ParseExact(time,
"HH:mm:ss",
System.Globalization.CultureInfo.CurrentCulture);
I am getting error:
String was not recognized as a valid DateTime.
I tried debug mode and I see the value :"30/12/1899 00:09:21" in the Variable time
when the value in the current execl column is:"00:09:21"
Where does the "30/12/1899" came from? Why is the string was not recognized as a valid DateTime?
Can I save only the format HH:mm:ss into sql server?
Try this, easy hack as my comment above.
string time = oledbReader[6].ToString().Split(" ".ToCharArray())[1];
DateTime streamingTime = DateTime.ParseExact(time, "HH:mm:ss",System.Globalization.CultureInfo.CurrentCulture);
or you could parse it as it is...
DateTime streamingTime = DateTime.ParseExact(time, "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
Since you didn't gave us any information about your CultureInfo, here with InvariantCulture;
string time = "30/12/1899 00:09:21";
DateTime streamingTime = DateTime.ParseExact(time, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Console.WriteLine(streamingTime);
Output will be;
12/30/1899 12:09:21 AM
Here a DEMO.
For more informations, check out Custom Date and Time Format Strings
Use a TimeSpan structure to hold a time value. A DateTime includes both a date and a time.
The problem is that excel not have time field and automatically convert time to date time field.
If course date is "empty" which means that it its a minimal date for excel - 30/12/1899
Moreover you don't have to invoke ToString methods because object is already a DateTime

DateTime Converted to Invalid Format

I tried converting 9/29/2013 2:44:28 PM (mm/dd/yyyy) to dd/mm/yyyy format.
I got a strange Date after Converting.
I tried
dateTimeVar.ToString("dd/mm/yyyy");
29/44/2013
The Date was a type of DateTime itself.
Lowercase mm means minutes, try this instead:
dateTimeVar.ToString("dd/MM/yyyy");
However, if this works depends on your local culture. If your current culture's date separator is different, / will be replaced with that. So if you want to enforce it use CultureInfo.InvariantCulture:
dateTimeVar.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
MM is for months, mm is for minutes. That's why it gets your minutes (which is 44) instead of your month value.
Use it like;
dateTimeVar.ToString("dd/MM/yyyy");
Check out;
The "MM" Custom Format Specifier
The "mm" Custom Format Specifier
And remember, / has special meaning when you use it as a date separator. It replace itself with your current culture date separator. Forcing to use with InvariantCulture would be better.
dateTimeVar.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
Take a look at;
The "/" Custom Format Specifier
What if I want to convert a string in dd/MM/yyyy to DateTime?
Then you can use DateTime.ParseExact method.
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format and culture-specific
format information. The format of the string representation must match
the specified format exactly.
As an example;
string s = "01/01/2013";
DateTime dt = DateTime.ParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(dt);
Output will be;
1/1/2013 12:00:00 AM
Here a DEMO.
dateTimeVar.ToString("dd/mm/yyyy"); // Change to dd/MM/yyyy
The problem is mm stands for minute and you need MM which would be months
Tim's answer is correct, but to remove the format string altogether you can use. 'ToShortDateString'
DateTime date = DateTime.Today;
var stringDate = date.ToShortDateString();
var stringDate2 = date.ToString("dd/MM/yyyy");

conversion from ddmmyyyy to mmddyyy

This is giving an exception:
String was not recognized as a valid DateTime.
string format = "MM/dd/yyyy hh:mm:ss.fff";
string dt_db1 = DateTime.ParseExact(txtTenureFrom.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture)
.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
DateTime d1 = DateTime.ParseExact(dt_db1, format, CultureInfo.InvariantCulture);
You didn't specify the input data, but the first part looks inconsistent with the second.
You start with a date value you expect to be in dd/MM/yyyy format, without a time component.
You convert it to a date value in MM/dd/yyyy format, still without out a time component.
You then try to parse it again in MM/dd/yyyy hh:mm:ss.fff format, expecting a time component to somehow be introduced in the string???
Where do you expect the time to magically come from?

Categories

Resources