C# Parsing Dates and Times - c#

I have some code in app along the lines of
DateTime activityDate = DateTime.Parse(tempDate + " " + tempTime);
Where tempDate is a string with values such as "2009-12-01" ( i.e. yyyy-mm-dd )
and tempTime is a string with values such as "23:12:10" ( i.e. hh:mm:ss )
Firstly, is there a better way to combine these to get a DateTime, and secondly is the code above safe to work in any region ( if not is there a way to handle this )
Hmm looking at the date more closely the concatenated date & time is actually in this format "2009-11-26T19:37:56+00:00" - what's the format string for the timezone part of the date/time?

If the format is guaranteed, ParseExact may be safer (sepcifying the pattern):
DateTime activityDate = DateTime.ParseExact(tempDate + " " + tempTime,
"yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

You can use ParseExact to specify the date and time format.
e.g.:
DateTime dateTime =
DateTime.ParseExact("2009-12-01 23:12:10", "yyyy-MM-dd HH:mm:ss", null);
Which yields:
Assert.That(dateTime, Is.EqualTo(new DateTime(2009, 12, 1, 23, 12, 10)));
You can also specify the culture that uses this format and parse using it the date and time while keeping the parsing safe from the processing OS culture.
From a quick look it seems that there is no culture with this exact predefined format, but in general many standard formats exists in the framework cultures.

Use ParseExact. It's been asked a few times on SO.. Link1, Link2

You can use ParseExact to specify a format for the parsing. That way there is no risk for it to be parsed in any other way:
DateTime activityDate = DateTime.ParseExact(tempDate + " " + tempTime, "yyyy'-'MM'-'dd HH':'mm':'ss", CultureInfo.InvariantCulture);

As if you cared, another option would be to do:
DateTime activityDateOnly =
DateTime.ParseExact(tempDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
TimeSpan activityTime =
TimeSpan.ParseExact(tempTime, "hh':'mm':'ss", CultureInfo.InvariantCulture);
DateTime activityDate = activityDateOnly + activityTime;
Just an option...

Related

How to parse datetime returns from ToString

When I use the following datetime format in the Windows calendar settings.
Short date: M/d
Long time: H:mm:ss
The following code can't work.
var s = DateTime.Now.ToString(); // 4/28 8:00:00
var b = DateTime.TryParse(s, out dt); // false
The string is returned from a library, so I cannot change it, is it possible to write a parsing method that works for any kind of datetime format in the Windows calendar settings?
Update, from #MathiasR.Jessen's suggestion, I have found a solution, but it is not elegant because I have to concatenate the format string manually.
var dtf = CultureInfo.CurrentCulture.DateTimeFormat;
var fmt = dtf.ShortDatePattern + " " + dtf.LongTimePattern;
var b = DateTime.TryParseExact(s, fmt, null, DateTimeStyles.None, out dt);
Now the question changes to is there a better way?
Note that DateTime.TryParse() or DateTime.Parse() will not understand just any custom format. For custom datetime formats you need to use DateTime.TryParseExact() and DateTime.ParseExact():
Here is a demo Demo with that would be able to parse your input string.
You can Use "DatetTime.Now.ToString("yyyy-MM-dd")" it returns the value in year-shortMonth-date.
You can change the format according to your code.

change format of datetime.now

I want to get the last seen of user and save it to my sql database in mvc5 . I got the last seen in controller with code like this:
users.userlast=DateTime.Now;
and saved to my database in this format "2015-08-06 12:12:13.443". I want to get datetime only format day,month,year, hour and minute.
I can't use something like this,
var dateTime = DateTime.ParseExact("12/02/21 10:56:09", "yy/MM/dd HH:mm", CultureInfo.InvariantCulture);
var text = dateTime.ToString("MMM. dd, yyyy HH:mm");
It did not work because my last seen column is a datetime type not string. What should i do?
Thanks.
Edit:
Like whatsup App., i want to see only hour and minute, not seconds as last seen.
You say that you are storing as a datetime type, in which case the you shouldn't need to convert a string to a DateTime. In fact you shouldn't need to do any parsing.
When you query the database you should get a DateTime, on which you can call the ToString() you want.
to get datetime in format day, month, year, hour and minute only (without seconds, milliseconds), create a new DateTime value before save:
var dt = DateTime.Now;
users.userlast = dt.Date.AddHours(dt.Hour).AddMinutes(dt.Minute);
You don't have to worry about the format you save in the database. When you want to represent it in your specific format you can ToString it accordingly.
I want to get datetime only format day,month,year, hour and minute.
string text = dateTime.ToString("yyyy-MM-dd HH:mm",
CultureInfo.InvariantCulture);
CultureInfo.InvariantCulture is to use your specified culture regardless of the user's current culture.
You can use InvariantCulture because your user must be in a culture that uses a dot instead of a colon:
DateTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
Just do like that
var formattedDateTime = yourLastSeenDateTime.ToString("MMM. dd, yyyy HH:mm", CultureInfo.InvariantCulture);
EDIT: Try this as you mentioned in comments
DateTime dbDate = yourLastSeenDateTime;
DateTime newDateTime = new DateTime(dbDate.Year, dbDate.Month, dbDate.Day, dbDate.Hour, dbDate.Minute, 0);

I am getting Error as String was not recognized as a valid DateTime

private string format = "dd/MM/yyyy HH:mm:ss";
DateTime fromdate = DateTime.ParseExact(GetFromScanDateTextBox.Text, format, CultureInfo.InvariantCulture);
I am getting error when executing this line string was not recognized as a Valid Date Time.
I have tried this also but it not works
DateTime fromdate = DateTime.ParseExact(GetFromScanDateTextBox.Text, format,null);
Your format string must be "d/M/yyyy", take a look at this.
Basically
MM : The month, from 01 through 12.
while
M : The month, from 1 through 12.
The same for the day part.
You are telling DateTime.ParseExact that you are expecting a string with format dd/MM/yyyy HH:mm:ss but you are giving it a string with format d/M/yyyy.
You need to change your format to just d/M/yyyy.
Also I suggest using DateTime.TryParseExact to verify the validity of your string instead of using exceptions.
var okay = DateTime.TryParseExact(
input,
new[] { "dd/MM/yyyy HH:mm:ss", "d/M/yyyy" },
new CultureInfo("en-GB"),
DateTimeStyles.None,
out dateTime);
If your input string is liable to change, TryParseExact allows you to define multiple formats as shown above, or alternatively, if it is always going to be with your current culture, just do DateTime.TryParse and do away with defining the format.
var okay = DateTime.TryParse(input, out dateTime);
If your format is always month/date/year and particularly in this case(if your date is 3rd Sept 2013) you can use:
string format = "MM/dd/yyyy";
string dateTime = "9/3/2013";
dateTime = (dateTime.Split('/')[0].Length == 1 ? "0" + dateTime.Split('/')[0] : dateTime.Split('/')[0]) + "/" + (dateTime.Split('/')[1].Length == 1 ? "0" + dateTime.Split('/')[1] : dateTime.Split('/')[1]) + "/" + dateTime.Split('/')[2];
DateTime fromdate = DateTime.ParseExact(dateTime, format, CultureInfo.InvariantCulture);
Do not provide the HH:MM:SS part in the format part
string format = "dd/MM/yyyy";
DateTime fromdate = DateTime.ParseExact(test.Text, format, CultureInfo.InvariantCulture);

DateTime - How can i account for different delimiter characters

My application is taking the time now, formatting it into a string, and parsing it back to a valid DateTime value using ParseExact. See below for more details:
DateTime dt = DateTime.Now;
DateTime timeNow = DateTime.Now;
string timeStamp = dt.ToString("MM/dd/yyyy HH:mm:ss");
// To match different countries
if (timeStamp.IndexOf("/") > -1)
{
timeNow = DateTime.ParseExact(timeStamp, "MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
}
else if (timeStamp.IndexOf(".") > -1)
{
timeNow = DateTime.ParseExact(timeStamp, "MM.dd.yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
}
Different countries use different date formats. Is there a way to make my application automatically take into account the different formats, rather than having to make a condition for each one that appears?
Thanks for any help,
Evan
If your application is using a string representation for dates internally, I would suggest using the Sortable format specifier when outputting it. That way, you always know that you can read it back using ParseExact and the "s" format specifier.
The only time you should output dates in any other format is when you need to display them for the user, or when some other program requires them in a particular format.
As #Mike Christensen pointed out in his comment, different locales will interpret dates differently. The default output for many European countries is DD/MM/YYYY, whereas in the U.S. it's usually MM/DD/YYYY. If you take the different locales into account, then there will be ambiguity.
You can pass an array of format specifiers with as many formats as you want to support.
string[] formats = new [] { "MM/dd/yyyy HH:mm:ss", "MM.dd.yyyy HH:mm:ss" };
DateTime d = DateTime.ParseExact
(
timestamp, formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None);
However, since you say you are generating the strings yourself, why don't you just make sure you always format them using the InvariantCulture:
string timestamp = dt.ToString("MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);

why this parse from string to DateTime fails in C#?

I have a DateTime eventDate field in my Mysql table which I compose from the inputs when I insert it in db:
cmd.Parameters.Add("?eventDate", MySqlDbType.DateTime).Value = DateTime.ParseExact(txtEventDate.Text + " " + txtEventTime.Text,
"MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
and is saved nice:
2011-05-05 10:20:00
Now, when I read it from DB I want to split it but it fails if I do like this:
txtEventDate.Text = DateTime.ParseExact(Reader.GetValue(7).ToString(), "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture).Date.ToShortDateString();
txtEventTime.Text = DateTime.ParseExact(Reader.GetValue(7).ToString(), "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture).TimeOfDay.ToString();
saying that:
String was not recognized as a valid DateTime.
Do you see any issue? I cannot figure out where I am wrong...
It seems superfluous to convert it to a string and parse it as a datetime and this may introduce problems with enexpected date formats.
If you have a Datetime in the database you could also do
txtEventDate.Text = Reader.GetDatetime(7).ToShortDateString();
txtEventTime.Text = Reader.GetDatetime(7).TimeOfDay().ToString();
To format DateTime try something like this...
DateTime date = Reader.GetDateTime(7);
txtEventDate.Text = date.ToString("MM/dd/yyyy");
txtEventTime.Text = date.ToString("HH:mm:ss");
You have to provide the right format. That may be:
yyyy-dd-MM HH:mm:ss

Categories

Resources