I am trying to capture input data from a Textbox by converting it to DateTime format
string yy = string.Format("{0:T}", textBox1.Text);
I wish to use Try-Catch-Finally to produce an Systm.FormatException error and display it in another text box
try
{
DateTime XF = Convert.ToDateTime(yy);
}
catch (FormatException)
{
textBox5.Text = "incorrect time";
}
finally
{
DateTime XF = Convert.ToDateTime(yy);
textBox5.Text = Convert.ToString(XF.Hour + XF.Minute + XF.Second);
}
How should i go around?
Thanks
Instead of using an exception to do this, it'd be better to use DateTime.TryParse. This will return a simple true or false if it can be converted into a date.
http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
DateTime xf;
bool canBeConverted = DateTime.TryParse(yy, out xf);
if (!canBeConverted) { textBox5.Text = "incorrect time"; }
You should use DateTime.TryParse() or DateTime.TryParseExact() if you're not sure if the format is correct. There's no need for exceptions, which are slow and less clear.
string dateString;
DateTime result;
if (DateTime.TryParse(dateString, result))
{
// it's a recognized as a DateTime
}
else
{
// it's not recognized as a DateTime
}
You can consider using DateTime.TryParseExact or DateTime.TryParse Method.
Eg.:
string dateString = "Mon 16 Jun 8:30 AM 2008";
string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateTime))
{
textBox5.Text = "correct time";
}
else
textBox5.Text = "incorrect time";
Try using DateTime.TryParse() method.
Related
I have to run through thousands of Word document and create XML files out of them. Everything works fine except the Date fields because I'm working in two languages.
Here are a few examples
DATE: NOVEMBER 24, 2016 TIME: 15:31
DATE: 28 NOVEMBRE 2016 HEURE: 10H31
I cleanup up the string a bit using the below but I still get the infamous 'String was not recognized as a valid DateTime.'
IFormatProvider culture = null;
if (m.rdoEnglish.IsChecked == true)
{
culture = new System.Globalization.CultureInfo("en-CA", true);
}
else if (m.rdoFrench.IsChecked == true)
{
culture = new System.Globalization.CultureInfo("fr-CA", true);
}
string dt = "";
dt = m.txtPublished.Text;
if (dt.IndexOf("HEURE:") != -1)
{
dt = dt.Replace("HEURE:", "");
}
if (dt.IndexOf("H") != -1)
{
dt = dt.Replace("H", ":");
}
DateTime dt2;
dt2 = DateTime.ParseExact(dt, "MM/dd/yyyy HH:mm:ss tt", culture);
//Cleaned string looks like this " 28 NOVEMBRE 2016 10:31 "
return dt2;
Looks like your format string is incorrect, in light of the two examples you gave.
It should be something like "MMMM dd, yyyy hh:mm"
Read more about it at:
DateTime.ParseExact Method
The ParseExact, as well TryParseExact, has an overload that accepts an array of formats to use in parsing the string. This will allow you to use something like this
string test = dt.Replace("DATE: ", "")
.Replace("TIME: ", "")
.Replace("HEURE: ", "");
string[] formats = new string[]
{
"MMMM dd, yyyy HH:mm", "dd MMMM yyyy HH\'H\'mm"
};
DateTime dt2 = DateTime.ParseExact(test, formats, culture, DateTimeStyles.None);
Notice that I don't try to replace the single char H inside the french version of your string because I don't know if the same char appears somewhere in your months.
string strDateFrom;
string strDateTo;
CrystalDecisions.Shared.ParameterDiscreteValue DateValue = new CrystalDecisions.Shared.ParameterDiscreteValue();
if ((strDateFrom != "") && (strDateTo != ""))
{
DateValue.Value = "(From: " + strDateFrom + " - " + strDateTo + ")";
}
else
{
DateValue.Value = "(ALL DATES)";
}
You can use DateTime.Parse
string date = "2020-02-02";
DateTime time = DateTime.Parse(date);
Console.WriteLine(time);
Or use:
DateTime oDate = DateTime.Parse(string s);
If you know the format used, you can try DateTime.ParseExact() or DateTime.TryParseExact():
String text = "30/12/2013";
DateTime result = DateTime.ParseExact(text, "d/M/yyyy", CultureInfo.InvariantCulture);
In order to avoid formatting issue, I prefer using DateTime.ParseExact or DateTime.TryParseExact.
basically the difference between those methods and DateTime.Parse is weather you know the date format of the string (and then you use DateTime.ParseExact) or not (and then use DateTime.Parse).
You can read more about ParseExact and TryParseExact
EDIT:
Example code from the links:
string dateString, format;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
// Parse date-only value with invariant culture.
dateString = "06/15/2008";
format = "d";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
// Parse date-only value without leading zero in month using "d" format.
// Should throw a FormatException because standard short date pattern of
// invariant culture requires two-digit month.
dateString = "6/15/2008";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
Can i convert the string below to DateTime
Friday, 27th September 2013
This is what i want to achieve:
String tmpDate="Friday, 27th September 2013";
closingDate = Convert.ToDateTime(tmpDate).ToString("yyyy-MM-dd");
Doing above i get error:
The string was not recognized as a valid DateTime. There is an unknown
word starting at index 10.
Well, I'm not sure there is exactly solution with -th, -st, -nd, but you can use this like;
string tmpDate = "Friday, 27 September 2013";
DateTime dt = DateTime.ParseExact(tmpDate,
"dddd, dd MMMM yyyy",
CultureInfo.InvariantCulture);
Here a DEMO.
I almost suggest you remove -th, -st and -nd part of your string but these are break the rules :)
August
Monday
Thursday
Sunday
Also check Habib's answer which seems nice.
You can maintain the ordinals to remove in an array like this (which might make it easier to add/remove ordinals from other languages). That way you don't have to manually remove the ordinal from each string input. Using TryParseExact avoids an exception being thrown if the DateTime could not be parsed from the string.
String tmpDate = "Friday, 27th September 2013";
string[] split = tmpDate.Split();
string[] ordinals = new string[] { "th", "nd", "st" };
foreach (string ord in ordinals)
split[1] = split[1].Replace(ord, "");
tmpDate = String.Join(" ", split);
DateTime dt;
if(DateTime.TryParseExact(tmpDate, "dddd, dd MMMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
Console.WriteLine("Parsed");
}
else
{
Console.WriteLine("Could not parse");
}
Your answer is in the exception you are getting. Obviously, "th" is not needed here. Just remove it and you are good to go.
This is working perfectly fine for me
String tmpDate = "Friday, 27 September 2013";
closingDate = Convert.ToDateTime(tmpDate).ToString("yyyy-MM-dd");
you will have to remove the th, nd,rd and st manually, as there isn't any format that takes these into account. After that you can use try parse exact like below
String tmpDate = "Friday, 27th September 2013";
tmpDate = tmpDate.Replace("nd", "")
.Replace("th", "")
.Replace("rd", "")
.Replace("st", "");
string[] formats = { "dddd, dd MMMM yyyy" };
DateTime dt;
if (DateTime.TryParseExact(tmpDate, formats, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out dt))
{
//parsing is successful
}
Assuming the format of the date string you provide does not change, the -st, -nd and -th can easily be removed (as already suggested).
Also be sure to provide a valid (existing) date, or a System.FormatException will be thrown.
string tmpDate = "Friday, 27th September 2013";
string[] splitDate = tmpDate.Split(new Char[] {' '});
splitDate[1] = splitDate[1].Substring(0, splitDate[1].Length-2);
string tmpDatewithoutStNdTh = String.Join(" ", splitDate);
try{
string closingDate = Convert.ToDateTime(tmpDatewithoutStNdTh).ToString("yyyy-MM-dd");
Console.WriteLine(closingDate.ToString());
}
catch(System.FormatException)
{
Console.WriteLine("The provided date does not exist.");
}
See http://msdn.microsoft.com/en-us/library/system.datetime.parse.aspx
public class Example
{
public static void Main()
{
string[] dateStrings = {"2008-05-01T07:34:42-5:00",
"2008-05-01 7:34:42Z",
"Thu, 01 May 2008 07:34:42 GMT"};
foreach (string dateString in dateStrings)
{
DateTime convertedDate = DateTime.Parse(dateString);
Console.WriteLine("Converted {0} to {1} time {2}",
dateString,
convertedDate.Kind.ToString(),
convertedDate);
}
}
}
I'm converting C# date time to string. Later when I convert it back to DateTime object it appears that they are not equal.
const string FMT = "yyyy-MM-dd HH:mm:ss.fff";
DateTime now1 = DateTime.Now;
string strDate = now1.ToString(FMT);
DateTime now2 = DateTime.ParseExact(strDate, FMT, CultureInfo.InvariantCulture);
Console.WriteLine(now1.ToBinary());
Console.WriteLine(now2.ToBinary());
Here is the example. Looks like everything is included in string format, when I print date both displays the same, but when I compare objects or print date in binary format I see the difference. It looks strange to me, could you please explain what is going on here?
Here is the output for the code above.
-8588633131198276118
634739049656490000
You should use the roundtrip format specifier "O" or "o" if you want to preserve the value of the DateTime.
The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information. For DateTime values, this format specifier is designed to preserve date and time values along with the DateTime.Kind property in text. The formatted string can be parsed back by using the DateTime.Parse(String, IFormatProvider, DateTimeStyles) or DateTime.ParseExact method if the styles parameter is set to DateTimeStyles.RoundtripKind.
Using your code (apart from changing the format string):
const string FMT = "O";
DateTime now1 = DateTime.Now;
string strDate = now1.ToString(FMT);
DateTime now2 = DateTime.ParseExact(strDate, FMT, CultureInfo.InvariantCulture);
Console.WriteLine(now1.ToBinary());
Console.WriteLine(now2.ToBinary());
I get:
-8588633127598789320
-8588633127598789320
Oded's answer is good but it didn't work for me for UTC dates. In order to get it to work for UTC dates, I needed to specify a DateTimeStyles value of "RoundtripKind" so that it didn't try to assume it was a local time. Here is the updated code from above:
const string FMT = "O";
DateTime now1 = DateTime.Now;
string strDate = now1.ToString(FMT);
DateTime now2 = DateTime.ParseExact(strDate, FMT, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
Console.WriteLine(now1.ToBinary());
Console.WriteLine(now2.ToBinary());
Note, this works for both UTC and local dates.
2 things:
You can use the ParseExact overload that takes a DateTimeStyle parameter in order to specify AssumeLocal.
There will still be a small difference between now1 and now2 unless you increase the precision to 7 digits instead of 3: "yyyy-MM-dd HH:mm:ss.fffffff"
const string FMT = "yyyy-MM-dd HH:mm:ss.fffffff";
DateTime now1 = DateTime.Now;
string strDate = now1.ToString(FMT);
DateTime now2 = DateTime.ParseExact(strDate, FMT, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
Console.WriteLine(now1.ToBinary());
Console.WriteLine(now2.ToBinary());
Even without the above changes, the calculated difference between now1 and now2 appears small, even though the binary values do not appear similar.
TimeSpan difference = now2.Subtract(now1);
Console.WriteLine(difference.ToString());
If you dont need the string to be human-readable (like, you want to cipher it before storage), you can just call string str = dt1.ToBinary().ToString(); and DateTime dt2 = DateTime.FromBinary(long.Parse(str));
DateTime now1 = DateTime.Now;
string strDate = now1.ToBinary().ToString();
DateTime now2 = DateTime.FromBinary(long.Parse(strDate));
Console.WriteLine(now1.ToBinary());
Console.WriteLine(now2.ToBinary());
Just use this code it convert date time to string and string to date time
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace DateTimeConvert
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = ConvDate_as_str(textBox1.Text);
}
public string ConvDate_as_str(string dateFormat)
{
try
{
char[] ch = dateFormat.ToCharArray();
string[] sps = dateFormat.Split(' ');
string[] spd = sps[0].Split('.');
dateFormat = spd[0] + ":" + spd[1] + " " + sps[1];
DateTime dt = new DateTime();
dt = Convert.ToDateTime(dateFormat);
return dt.Hour.ToString("00") + dt.Minute.ToString("00");
}
catch (Exception ex)
{
return "Enter Correct Format like <5.12 pm>";
}
}
private void button2_Click(object sender, EventArgs e)
{
label2.Text = ConvDate_as_date(textBox2.Text);
}
public string ConvDate_as_date(string stringFormat)
{
try
{
string hour = stringFormat.Substring(0, 2);
string min = stringFormat.Substring(2, 2);
DateTime dt = new DateTime();
dt = Convert.ToDateTime(hour+":"+min);
return String.Format("{0:t}", dt); ;
}
catch (Exception ex)
{
return "Please Enter Correct format like <0559>";
}
}
}
}
Say I have the following:
string fromTime = "8:00am";
string someDate = "06/01/2012";
I want to end up doing this:
DateTime dt = Convert.ToDateTime(someDate + someTime);
Basically I want to take a date and add the time to it with the result for the above to be
06/01/2012 8:00am
But have it stored in a datetime variable. Is this possible?
You could use the DateTime.TryParseExact method which allows you to specify a format when parsing:
class Program
{
static void Main()
{
string s = "06/01/2012 8:00am";
string format = "dd/MM/yyyy h:mmtt";
DateTime date;
if (DateTime.TryParseExact(s, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
Console.WriteLine(date);
}
}
}
Try this:
DateTime dt = DateTime.ParseExact(someDate + " " + someTime, "MM/dd/yyyy h:mmtt", CultureInfo.InvariantCulture);