Update
I want to display a date time value in 24 hour format for either UK or US depending on its current culture, using generic way.
The code is below (NOT the actual code, it is for the question only):
var dt = new DateTime(2011, 4, 15, 17, 50, 40);
Console.WriteLine(dt.ToString("d", new CultureInfo("en-us")) + " "
+ dt.ToString("H:mm:ss", new CultureInfo("en-us")));
Console.WriteLine(dt.ToString("G", new CultureInfo("en-gb")));
Result below:
4/15/2011 17:50:40
15/04/2011 17:50:40
It displays ok.
Is there a better way to display the time without using "H:mm:ss". Please note that The G for US display PM, which is not what I want.
The month is 4 for US, rather than 04, is there a way to display it in 04.
.
Update
Below is what I want, ideally using generic way:
US: 04/15/2011 17:50:40
UK: 15/04/2011 17:50:40
Try this.
DateTime dt = new DateTime(2011, 4, 15, 17, 50, 40);
Console.WriteLine(dt.ToString("MM/dd/yyy H:mm:ss"));// US format
Console.WriteLine(dt.ToString("dd/MM/yyy H:mm:ss"));// UK format
Custom Date and Time Format Strings from MSDN
You can write your own custom display like this,
DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString(#"MM/dd/yy HH\:mm\:ss"));
Console.ReadLine();
// Displays 05/20/12 17:08:37
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
You can do something like this for US:
CultureInfo ci = new CultureInfo("en-us", true);
ci.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
ci.DateTimeFormat.LongTimePattern = "HH:mm:ss";
ci.DateTimeFormat.AMDesignator = "";
ci.DateTimeFormat.PMDesignator = "";
Now you can either set the current thread culture like this:
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
And display the date like this:
Console.WriteLine(dt.ToString("G"));
Or you can pass the culture as a parameter to the ToString method like this:
Console.WriteLine(dt.ToString("G", ci));
If you prefer the second method you can wrap the code above in a static method so you can call it like this:
Console.WriteLine(dt.ToString("G", Cultures.EnUs));
Related
I'm reading in a date from a textbox into a C# program and comparing to a date to entries in a SQL database. I can't get them to match, despite a SQL query of the date showing there are entries for that date.
I've tried saving to a variable with .Date to try and strip off the hh:mm:ss, which had no results. I've attempted DateTime.ParseExact to change the format to match the database.
if (!System.String.IsNullOrEmpty(searchDate))
{
CultureInfo culture = new CultureInfo("en-US");
DateTime completeDate = DateTime.ParseExact(searchDate, "M/d/yyyy", culture);
requests = requests.Where(x => x.CompletionDate == completeDate);
}
I expect to find a match for two records in the database when I search for 1/28/2019. I'm getting no results. I've tried other entries and also not found any matches. No error messages are being generated.
If you simply compare two DateTime objects, they will consider not only date but also time.
To compare just the date, you can use DateTime.Date property.
var date1 = new DateTime(2019, 7, 29, 15, 23, 44);
var date2 = new DateTime(2019, 7, 29);
Console.WriteLine(date1 == date2);
Console.WriteLine(date1.Date == date2.Date);
The first will return false, the second will return true in this case.
The issue is time isn't a factor your comparison and shouldn't be included. You need to explicitly compare date parts only...
requests = requests.Where(x => x.CompletionDate.Date == completeDate.Date);
CultureInfo culture = new CultureInfo("en-US");
DateTime completeDate = DateTime.ParseExact(searchDate, "M/d/yyyy", culture);
completeDate = 1/28/2019 12:00:00 AM
if the date stored in db is 1/28/2019 it wont match.
How do I use a specific date as an input value?
var experiment1 = WorkingWithDates.GetDisplayString("London", DateTime.Today, 45.00);
Later on, I'll be convering it to a string, but I need it to be input as a DateTime.
public static string GetDisplayString(string city, DateTime date, double temp)
{
}
I'm using DateTime.Today as a placeholder, simply because it works. The thing is, I need it input as a specific day of a month of a year. (I've tried using (10, 10, 10) but it simply gives me a compiler error.
Edit.: I can't believe I did not figure out all I need to do is to add "new". Thanks folks
In (10, 10, 10) do you want the year 10?
Use the constructor that takes in a year, a month and a day. As below.
DateTime dt = new DateTime(2013, 12, 12);
then call your method
var experiment1 = WorkingWithDates.GetDisplayString("London", dt, 45.00);
PS: If you want year 10
DateTime dt = new DateTime(10, 10, 10);
will work. The year will be 0010
WorkingWithDates.GetDisplayString("London", DateTime.Today, 45.00);
you need a DateTime object to be used in place of DateTime.Today, so construct your instance using
DateTime newdate = new DateTime(2013,10,10) // year, month , day
and then
WorkingWithDates.GetDisplayString("London", newdate, 45.00);
I'm working on an app that may be seen in many countries in the world. There are not many countries that show hours, minutes and seconds with something other than : as a seperator but there are a few and I want to make sure that times are formatted correctly for their region. DateTime is great at this but TimeSpan isn't. These snippets are from my immediate Window in Visual Studio 2010 using .Net 4 with my region set to Malayalam (India). The dateTime.Now call also reflects how time is shown on my clock, Microsoft Outlook and other areas.
DateTime.Now.ToString()
"02-10-12 17.00.58"
http://msdn.microsoft.com/en-us/library/dd784379.aspx Says "If formatProvider is null, the DateTimeFormatInfo object that is associated with the current culture is used. If format is a custom format string, the formatProvider parameter is ignored." It stands to reason then that i shouldn't need to even pass in the Current CultureInfo. The format i want here is hh.mm.ss but obvioulsy hh:mm:ss when in most other languages, and if there are anoy other poossibilities, it should automatically reflect those too - basically TimeSpan should be culture-Aware, just as DateTime is.
However:
timeRemaining.ToString()
"00:02:09"
timeRemaining.ToString("c")
"00:02:09"
timeRemaining.ToString("c", CultureInfo.CurrentCulture)
"00:02:09"
timeRemaining.ToString("g")
"0:02:09"
timeRemaining.ToString("G")
"0:00:02:09.0000000"
timeRemaining.ToString("t")
"00:02:09"
timeRemaining.ToString("g", CultureInfo.CurrentCulture)
"0:02:09"
timeRemaining.ToString("g", CultureInfo.CurrentUICulture)
"0:02:09"
timeRemaining.ToString("G", CultureInfo.CurrentUICulture)
"0:00:02:09.0000000"
timeRemaining.ToString("G", CultureInfo.CurrentCulture)
"0:00:02:09.0000000"
timeRemaining.ToString("t", CultureInfo.CurrentCulture)
"00:02:09"
I'm looking for a simple, single line to output a timeSpan in a culture-Aware manner. Any ideas are appreciated.
Looks like a bug, you can report it at connect.microsoft.com. Meanwhile, a workaround is to take advantage of DateTime formatting. Like this:
using System;
using System.Globalization;
class Program {
static void Main(string[] args) {
var ci = CultureInfo.GetCultureInfo("ml-IN");
System.Threading.Thread.CurrentThread.CurrentCulture = ci;
var ts = new TimeSpan(0, 2, 9);
var dt = new DateTime(Math.Abs(ts.Ticks));
Console.WriteLine(dt.ToString("HH:mm:ss"));
Console.ReadLine();
}
}
Output:
00.02.09
This is more like a comment, but needs some space, so I write it as an answer.
While string formatting of DateTime has been in .NET for a very long time, formatting of TimeSpan was new in .NET 4.0 (Visual Studio 2010).
A culture has a DateTimeFormatInfo object which is used by DateTime and includes info on whether to use colon : or period . or something else between hours, minutes and seconds. Now, TimeSpan does not seem to use this DateTimeFormatInfo object, and there is nothing called "TimeSpanFormatInfo".
Here's an example:
// we start from a non-read-only invariant culture
Thread.CurrentThread.CurrentCulture = new CultureInfo("");
// change time separator of DateTime format info of the culture
CultureInfo.CurrentCulture.DateTimeFormat.TimeSeparator = "<-->";
var dt = new DateTime(2013, 7, 8, 13, 14, 15);
Console.WriteLine(dt); // writes "07/08/2013 13<-->14<-->15"
var ts = new TimeSpan(13, 14, 15);
Console.WriteLine(ts); // writes "13:14:15"
I'm looking for a simple, single line to output a timeSpan in a culture-Aware manner.
Then I think you're best off using the DateTime class to do the formatting for you:
string display = new DateTime(timespan.Ticks).ToLongTimeString();
Assuming that timespan holds a positive duration between 0 and 24 hours long.
I currently have a program that takes the value from a datePicker and have the date saved as a string. I only needed the date not the time so i used the following code to save the date value:
DateTime StartDate;
String inMyString;
savedDate = datePicker1.SelectedDate.Value.Date;
inMyString = savedDate.Date.ToShortDateString()
I have the inMyString pushedBack into my list and now i want to place it back into the datePicker.
On MSDN is shows me the following example to set the date.
dateTimePicker1.Value = new DateTime(2001, 10, 20);
the problem is that having .Value after my date picker is not an option (it doesn't show in Intellisense.)
I have also tried
datePicker1.SelectedDate.Value= new DateTime(inMyString)
and also converting the inMyString to type DateTime but it still does not work.
Any thoughts on how to do this?
Any Suggestions and comments are appreciated.
Thanks!
Try this:
datePicker1.SelectedDate = new DateTime(2001, 10, 20);
If you need to take datetime from string:
datePicker1.SelectedDate = DateTime.Parse(inMyString);
Side note:
You can replace those 3 lines:
String inMyString;
savedDate = datePicker1.SelectedDate.Value.Date;
inMyString = savedDate.Date.ToShortDateString();
with one:
var inMyString = datePicker1.SelectedDate.Value.ToShortDateString();
Another side note: don't know if there is a reason to it, but you might consider storing datetime as dattime, not as a string.
If you want to show today's date in WPF C#, use this method:
datePicker1.SelectedDate = DateTime.Today.AddDays(-1);
I have a query like i want to show the time information in custom format like(1min 06sec) from date .I have a filed Duration in database and when i am binding my data control then in item i want to display in above format(1min 06 sec),so is it possible?
Checkout this documentation - http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
But, assuming you have a DateTime object, something like this should do the trick:
var test1 = DateTime.UtcNow.ToString("m'min 's'sec'");
Or for a TimeSpan:
var test2 = TimeSpan.FromSeconds(123).ToString("m'min 's'sec'");
You can easily add in hours/days/etc. depending on the exact format you want. If your object isn't a DateTime or TimeSpan object, you will have to do something custom.
You can use System.TimeSpan structure. It represents time interval.
MSDN
Given you DateTime variable, you could do the following:
var rr = dt1.ToString("mm'min 'ss'sec'");
Or if you have a TimeSpan:
You'll need to use a TimeSpan for this. A simplistic approach is the following:
var ts = new TimeSpan(0, 2, 30);
var result = ts.Minutes.ToString() + "min " + ts.Seconds.ToString() + "sec";
In this example, I've set the TimeSpan variable to 2 minutes and 30 seconds.
Or if you have two dates:
If you have two dates you can do a diff and get the timespan and from there use the code I've shown above:
var dt1 = new DateTime(2011, 01, 01, 12, 01, 00);
var dt2 = new DateTime(2011, 01, 01, 12, 03, 30);
var diffTimeSpan = dt2.Subtract(dt1);
var r = diffTimeSpan.Minutes.ToString() + "min " + diffTimeSpan.Seconds.ToString() + "sec";