C#: How would I get the current time into a string? - c#

How could I get the current h/m/s AM time into a string? And maybe also the date in numeric form (01/02/09) into another one?

I'd just like to point out something in these answers. In a date/time format string, '/' will be replaced with whatever the user's date separator is, and ':' will be replaced with whatever the user's time separator is. That is, if I've defined my date separator to be '.' (in the Regional and Language Options control panel applet, "intl.cpl"), and my time separator to be '?' (just pretend I'm crazy like that), then
DateTime.Now.ToString("MM/dd/yyyy h:mm tt")
would return
01.05.2009 6?01 PM
In most cases, this is what you want, because you want to respect the user's settings. If, however, you require the format be something specific (say, if it's going to parsed back out by somebody else down the wire), then you need to escape these special characters:
DateTime.Now.ToString("MM\\/dd\\/yyyy h\\:mm tt")
or
DateTime.Now.ToString(#"MM\/dd\/yyyy h\:mm tt")
which would now return
01/05/2009 6:01 PM
EDIT:
Then again, if you really want to respect the user's settings, you should use one of the standard date/time format strings, so that you respect not only the user's choices of separators, but also the general format of the date and/or time.
DateTime.Now.ToShortDateString()
DateTime.Now.ToString("d")
Both would return "1/5/2009" using standard US options, or "05/01/2009" using standard UK options, for instance.
DateTime.Now.ToLongDateString()
DateTime.Now.ToString("D")
Both would return "Monday, January 05, 2009" in US locale, or "05 January 2009" in UK.
DateTime.Now.ToShortTimeString()
DateTime.Now.ToString("t");
"6:01 PM" in US, "18:01" in UK.
DateTime.Now.ToLongTimeString()
DateTime.Now.ToString("T");
"6:01:04 PM" in US, "18:01:04" in UK.
DateTime.Now.ToString()
DateTime.Now.ToString("G");
"1/5/2009 6:01:04 PM" in US, "05/01/2009 18:01:04" in UK.
Many other options are available. See docs for standard date and time format strings and custom date and time format strings.

You can use format strings as well.
string time = DateTime.Now.ToString("hh:mm:ss"); // includes leading zeros
string date = DateTime.Now.ToString("dd/MM/yy"); // includes leading zeros
or some shortcuts if the format works for you
string time = DateTime.Now.ToShortTimeString();
string date = DateTime.Now.ToShortDateString();
Either should work.

Method to get system Date and time in a single string
public static string GetTimeDate()
{
string DateTime = System.DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss");
return DateTime;
}
sample OUTPUT :-16-03-2015 07:45:15

DateTime.Now.ToString("h:mm tt")
DateTime.Now.ToString("MM/dd/yyyy")
Here are some common format strings

Be careful when accessing DateTime.Now twice, as it's possible for the calls to straddle midnight and you'll get wacky results on rare occasions and be left scratching your head.
To be safe, you should assign DateTime.Now to a local variable first if you're going to use it more than once:
var now = DateTime.Now;
var time = now.ToString("hh:mm:ss tt");
var date = now.ToString("MM/dd/yy");
Note the use of lower case "hh" do display hours from 00-11 even in the afternoon, and "tt" to show AM/PM, as the question requested. If you want 24 hour clock 00-23, use "HH".

string t = DateTime.Now.ToString("h/m/s tt");
string t2 = DateTime.Now.ToString("hh:mm:ss tt");
string d = DateTime.Now.ToString("MM/dd/yy");
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Related

DateTime Format - Any System Datetime.now to "DD/MM/YYYY hh:mm:ss"

I have a program that do several things.
Two of them is read a date from a txt and rewrite a date in the same txt.
The read of the date is a regex expression like:
[0-9]{2}/[0-9]{2}/[0-9]{4} [0-9]{2}:[0-9]{2}:[0-5]{1}[0-9]{1})
The problem is that my regex expression only works in the format
"DD/MM/YYYY hh:mm:ss" and its impossible to make sure my regex expression can match all system datetime formats.
So, I need to make sure my program run's in every system, regardless the system datetime.now.
For that, i thought about format every system datetime.now, at start, to the format mentioned "DD/MM/YYYY hh:mm:ss".
At the moment i have the following code:
Datetime currentDate = DateTime.ParseExact(DateTime.Now.ToString(), "DD/MM/YYYY hh:mm:ss", CultureInfo.InvariantCulture);
However, when running some tests, using a system date in format "D/M/YYYY h:m:s" i get the error:
"String was not recognized as a valid DateTime."
The problem is that if my date, for example, is "9/27/2019 04:26:46"(M/D/YYYY h:m:s) it can't fit in the format i defined.
Any idea?
Thank you in advance!
You need to use the same format string and culture in every place where you convert the DateTime to string as well. In your sample code, you're doing
DateTime.Now.ToString()
This uses the default culture for the thread, and the default format. Unless assigned otherwise, the thread is probably using the local culture info. Instead, you would want to use the same format and the invariant culture:
DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
(note the lowercase "dd". "DD" is not a valid format specifier for date times; these things are case sensitive. Also note the "HH", which gives a 24-hour value, rather than 12-hour)
In practice, just using the invariant culture should be enough for persistence. Cultures already include default datetime formats, so unless you have a specific need to use a different format, why not use the default?
Also note that DateTime doesn't have a format. The format only comes into play when you convert from or to a string. That is the place where you need to ensure the same culture and format is used for both sides of the operation (and that's why for persistence, especially for data shared between different users or computers, you generally want to use the invariant culture).
If you need
to make sure my program run's in every system, regardless the system datetime.now
you can adapt international standard for this, say, ISO 8601.
In order to validate the DateTime, regular expressions like you have are not enough (just imagine leap years), but TryParse does it job:
string source = "2019-09-26T23:45:59";
// Either current culture date and time format or ISO
bool isValid = DateTime.TryParse(
source,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal,
out var _date);
Or if you want to be more restrictive use TryParseExact:
// ISO only
bool isValid = DateTime.TryParseExact(
source,
"s",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal,
out var _date);
If you want to represent DateTime.Now in ISO 8601, add "s" standard format string:
string dateAsString = DateTime.Now.ToString("s");
Alas, you can provide a bunch of formats which are able to cope with any date and time formats; a classical example of ambiguous date is
01/02/03 - 01 Feb 2003 (Russia)
01/02/03 - 02 Jan 2003 (USA)
01/02/03 - 03 Feb 2001 (China)
You can alleviate the problem, while providing several formats:
// Here we try to support 4 formats (note different delimeters)
string[] formats = new string[] {
"s", // try ISO first
"dd'.'MM'.'yyyy HH':'mm':'ss", // if failed try Russian
"MM'/'dd'/'yyyy HH':'mm':'ss", // on error have a look at USA
"yyyy'-'MM'-'dd HH':'mm':'ss", // the last hope is Chinese
};
bool isValid = DateTime.TryParse(
source,
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal,
out var date);

Unable to convert from string to datetime C#

I am trying to parse a string to Datetime, but it is not working and giving an error:
"String was not recognized as a valid DateTime."
The string is perfect.
Here is the code:
string deliv = DeliveryDateTextBox.Text;
string[] delivday = deliv.Split('-');
int year, month, day;
int.TryParse(delivday[0], out day);
int.TryParse(delivday[1], out month);
int.TryParse(delivday[2], out year);
string dtt = day + "/" + month + "/" + year;
DateTime datet = DateTime.ParseExact(dtt, "dd/MM/yyyy", null);
jobcard.DeliveryDate = datet;
I debugged the code and it is giving {01-01-0001 12:00:00 AM} on datet.
Besides the fact that you should be using new DateTime(year, month, day), or even DateTime.TryParseExact(deliv, "d-M-yyyy", .... ) on the original string...
Your call to DateTime.ParseExact() is failing because your input string has single-digit day and/or single-digit month, while your pattern dd/MM/yyyy demands double digits for both.
This can be fixed by using d/M/yyyy for the pattern, it will accept single and double digits. But please don't, see the first paragraph!
You over complicated things in this code.
Manually parsing the string to extract int values of day, month and year just to recombine them into a new string and parsing it makes no sense.
Simply try to parse the original string:
DateTime datet;
if(DateTime.TryParseExact(
DeliveryDateTextBox.Text,
"dd-MM-yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out datet))
{
// string was successfully parsed to dateTime.
}
There is no "perfect" DateTime String. How you can can/should represent a DateTime is dependent 100% on the CultureFormat of Windows, which can be totally different even within a langauge: For example en-gb and en-us disagree on what the decimal, thousand seperator are and in which order the date components should be listed.
Your whole code does not make a lot of sense. It seems you have some disjointed textboxes where the user inputs the day, month and year seperately. Then you parse them to int. Then you turn them into a string. Then you try to parse the string.
And at no point do you even check if the original user inputs are valid. That original parsing to Int might already fail. So you might try to parse 0/0/0 into a DateTime. To which your output is actually the perfect answer. And then there is stuff like anything before 1800 or so being literally not on the Gregorian calendar.
If you want the user to input a date, use a DatePicker element. Every GUI technology I know of has one. They give you DateTimes as return value. Do not try your custom workaround.

C# how to change date format DD.MM.YY to DD/MM/YY using DateTime.ParseExact Method

In my code I need to handle two types of datetime formats. if the input date is a like 8/31/2017 12:00:00 AM I just wanna save it. But when it comes with the format like "25.11.13" I wanna convert it like this 11/25/2013 12:00:00 AM and wanna save it.
Somehow I managed my code but the problem is the "else block" is not working as expected (actually it won't work at all).
DateTime registrationDate = new DateTime();
if (DateTime.TryParse(myTable.Rows[i][6].ToString(), out registrationDate))
{
record.RegistrationDate = !string.IsNullOrEmpty(detailsTable.Rows[i][6].ToString()) ? Convert.ToDateTime(detailsTable.Rows[i][6].ToString()) : (DateTime?)null;
}
else
{
DateTime.TryParse(detailsTable.Rows[i][6].ToString(), out registrationDate);
record.RegistrationDate = registrationDate;
}
I think you have a culture issue here. "8/31/2017" is clearly in US format M/D/Y because no month has 31 days. However "25.11.13" is in another D/M/Y (possibly UK) format.
Unless your detailsTable contains the culture the value is in you are stuck here. This is because it is impossible to tell if 9/11/2001 is the 9th of November or 11th of September without further information.
DateTime.TryParse will try to use the culture of the user that is running the code. Note if it is a web site then it runs as the account the IIS Service is set to use. There is an overload of TryParse that takes another parameter that allows you to tell it which culture the supplied string is in.
If you know that all dates that have slashes '/' are in US format and all dates that have dots '.' are in UK format then you can pre-parse the string to enable you to tell TryParse the correct culture. Like this:
static DateTime Parse(string input)
{
CultureInfo ci =
CultureInfo.CreateSpecificCulture(
input.Contains(".") ?
"en-GB" :
"en-US");
DateTime result;
DateTime.TryParse(input, ci, DateTimeStyles.None, out result);
return result;
}

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

I have a WP8 app, which will send the current time to a web service.
I get the datetime string by calling
DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff")
For most users it works great and gives me the correct string like "09/10/2013 04:04:31.415". But for some user the resulted string is something like "09/14/2013 07.20.31.371", which causes problem in my web service.
Is it because some culture format issue? How can I make sure the result string is delimited by colon instead of dot?
Is it because some culture format issue?
Yes. Your user must be in a culture where the time separator is a dot. Both ":" and "/" are interpreted in a culture-sensitive way in custom date and time formats.
How can I make sure the result string is delimited by colon instead of dot?
I'd suggest specifying CultureInfo.InvariantCulture:
string text = dateTime.ToString("MM/dd/yyyy HH:mm:ss.fff",
CultureInfo.InvariantCulture);
Alternatively, you could just quote the time and date separators:
string text = dateTime.ToString("MM'/'dd'/'yyyy HH':'mm':'ss.fff");
... but that will give you "interesting" results that you probably don't expect if you get users running in a culture where the default calendar system isn't the Gregorian calendar. For example, take the following code:
using System;
using System.Globalization;
using System.Threading;
class Test
{
static void Main()
{
DateTime now = DateTime.Now;
CultureInfo culture = new CultureInfo("ar-SA"); // Saudi Arabia
Thread.CurrentThread.CurrentCulture = culture;
Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
}
}
That produces output (on September 18th 2013) of:
11/12/1434 15:04:31.750
My guess is that your web service would be surprised by that!
I'd actually suggest not only using the invariant culture, but also changing to an ISO-8601 date format:
string text = dateTime.ToString("yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture);
This is a more globally-accepted format - it's also sortable, and makes the month and day order obvious. (Whereas 06/07/2013 could be interpreted as June 7th or July 6th depending on the reader's culture.)
: has special meaning: it is The time separator. (Custom Date and Time Format Strings).
Use \ to escape it:
DateTime.ToString(#"MM/dd/yyyy HH\:mm\:ss.fff")
Or use CultureInfo.InvariantCulture:
DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture)
I would suggest going with the second one, because / has special meaning as well (it is The date separator.), so you can have problems with that too.
You can use InvariantCulture because your user must be in a culture that uses a dot instead of a colon:
DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);
I bumped into this problem lately with Windows 10 from another direction, and found the answer from #JonSkeet very helpful in solving my problem.
I also did som further research with a test form and found that when the the current culture was set to "no" or "nb-NO" at runtime (Thread.CurrentThread.CurrentCulture = new CultureInfo("no");), the ToString("yyyy-MM-dd HH:mm:ss") call responded differently in Windows 7 and Windows 10. It returned what I expected in Windows 7 and HH.mm.ss in Windows 10!
I think this is a bit scary! Since I believed that a culture was a culture in any Windows version at least.
You can use String.Format:
DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}.{6:000}", d.Month, d.Day, d.Year, d.Hour, d.Minute, d.Second, d.Millisecond);
// I got this result: "02/23/2015 16:42:38.234"
Convert Date To String
Use name Space
using System.Globalization;
Code
string date = DateTime.ParseExact(datetext.Text, "dd-MM-yyyy", CultureInfo.InstalledUICulture).ToString("yyyy-MM-dd");

How to convert string to local Date Time?

I am trying to convert a string of this format:
MM/dd/yyyy HH:mm
The input is from a US database, so, i.e.:
09/20/2010 14:30
I know that my string is always US time but when I display it, I need to translate that into the local time, so that string should be turned into:
09/20/2010 19:30 (for UK for instance)
I tried a few things but nothing seems to give me the correct solution when I run on a US machine vs a UK or Ge machine
I tried:
CompletedDttm = DateTime.ParseExact(value, "MM/dd/yyyy HH:mm", CultureInfo.CurrentCulture);
CompletedDttm = DateTime.ParseExact(value, "MM/dd/yyyy HH:mm", new CultureInfo("en-US"));
They all work locally (US machine) but they don't convert the time to local time on a European machine.
Thanks
Tony
Try this - it converts local time (input in US format) to GMT and then prints in GB/DE format.
var zones = TimeZoneInfo.GetSystemTimeZones(); // retrieve timezone info
string value = "09/20/2010 14:30";
DateTime CompletedDttm = DateTime.ParseExact(value, "MM/dd/yyyy HH:mm",
new CultureInfo("en-US"));
DateTime FinalDttm = TimeZoneInfo.ConvertTime(CompletedDttm,
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"),
TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time"));
string output = FinalDttm.ToString(new CultureInfo("en-GB"));
FinalDttm = TimeZoneInfo.ConvertTime(CompletedDttm, TimeZoneInfo.Local,
TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"));
output = FinalDttm.ToString(new CultureInfo("de-DE"));
Output is, in turn:
20/09/2010 19:30:00
20.09.2010 20:30:00
UPDATE: You have to know the timezone of the data (not just that it is "US") as well as the interpreting machine if you want to reliably convert it to anything else. You're not only looking at hours offset, but DST also which varies by location (not all locales abide by it). Eastern is either -4 or -5 depending on the time of year. And if the date is old enough you run into the issue that "summer" dates were changed recently.
Your best course is to ALWAYS store timestamps in UTC. Aside from that, you can just make guesses about the offset.
You should be working with UTC times (the new, slightly different, version of GMT) if you want to be converting to other time zones.
DateTime dt = new DateTime(DateTime.Parse('2010-10-06 19:40').Ticks, DateTimeKind.Local);
dt.AddHours(5);
dt.ToLocalTime();
You could also make use of TimeZoneInfo which will have DST information also.
Unless you specify otherwise, the parse will assume you mean to parse the string into your current timezone. US culture just means the expected format of the string, and has nothing to do with the timezone (for example, in the US it could be EST or it could be PST).
Your string contains no timezone information, so naturally you're going to get your value in whatever the local timezone is. You can either:
Add the timezone info
Change the timezone afterwards
I think it's a display problem, but need more info to be sure. Try displaying the dates in yyyy-MM-dd format in both cases to check if the problem is on parse or display. You can create a custom format info object if you know exactly what you want to accept or display:
public static DateTimeFormatInfo GetISOFormatInfo()
{
DateTimeFormatInfo dtFormat = new DateTimeFormatInfo();
dtFormat.DateSeparator = "-";
dtFormat.TimeSeparator = ":";
dtFormat.ShortDatePattern = "yyyy-MM-dd";
dtFormat.ShortTimePattern = "HH:mm:ss";
return dtFormat;
}
Using a Date without TimeZone information, you will not be able to know the UK time / Canada time etc... since you do not know who (which part of the world) instered that time. Since you specifically said that the time is US time, you can add the time difference for the different parts of the world to display the local time.
You could use string.Split. first with the '/' separator on the whole string. You will get "09" "20" and "2010 14:30" then apply the split 2 more times with ' ' and ':'

Categories

Resources