Converting a year string i.e. '2005' to a Datetime value - c#

I am creating a simple input form to create an account. On the form there is an input field for the year the company was founded, this is a simple textbox where the user will type in the year i.e. 2005.
However on attempting to insert this to the database field which is a datetime an error is being thrown despite converting the textbox entry to datetime...
myCompanyAccount.Founded = Convert.ToDateTime(this.TxtCompanyFounded.Text);
Is there a way in which i can can convert a year input i.e. 2005 to a datetime so it can be inserted to the database...? Thanks in advance!

It happens just because 2005 is not a standart date and time format and that's the reason Convert.ToDateTime will fail.
You can use DateTime.TryParseExact or DateTime.ParseExact methods instead to parse your custom date and time like;
string s = "2005";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
dt will be 01/01/2005 00:00:00 (of course it's representation depends on your current culture in .ToString() method)
Here a demonstration.

You should create a new DateTime and just enter default days / months if you don't need them, for example:
MyCompany.Founded = new DateTime(Convert.ToInt32(this.TxtCompanyFounded.Text), 1, 1);

use
myCompanyAccount.Founded = new DateTime(int.parse(TxtCompanyFounded.Text), 1, 1)
this will insert a date of 1 january + year

You cannot convert a string or int to datetime..So you have to format it like a date..Try this..
int year=convert.toint32(TxtCompanyFounded.Text);
DateTime Date= new DateTime(year, 1, 1);

If the user can only enter a year, consider simply:
var date = Convert.ToDateTime(str + "-01-01");
It's not the "cleanest" but it will do the trick (FSVO) - however, maybe the database column should just be a YEAR and not a DATETIME?

Do something like this in insert query,
Insert into table (starteddate) values (Convert.ToDateTime('"+TextBox1.Text+"'))

You can use DateTime.TryParseExact, providing a list of all the formats you want to accept.
E.g.:
string[] validFormats = new[] {
"yyyy",
"MM/yyyy",
"MM/dd/yyyy"
};
DateTime result;
var success = DateTime.TryParseExact("2005", validFormats,
CultureInfo.InvariantCulture, DateTimeStyles.None, out result);

You use:
myCompanyAccount.Founded =
DateTime.ParseExact(this.TxtCompanyFounded.Text, "yyyy", null);
or more securely:
DateTime result;
bool canParse = DateTime.TryParseExact(this.TxtCompanyFounded.Text,
"yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
if (canParse)
{
myCompanyAccount.Founded = result;
}
else
{
// take care of problematic input
}

Related

Error: String was not recognised as a valid Datetime format [duplicate]

I have a string like this:
250920111414
I want to create a DateTime object from that string. As of now, I use substring and do it like this:
string date = 250920111414;
int year = Convert.ToInt32(date.Substring(4, 4));
int month = Convert.ToInt32(date.Substring(2, 2));
...
DateTime dt = new DateTime(year, month, day ...);
Is it possible to use string format, to do the same, without substring?
Absolutely. Guessing the format from your string, you can use ParseExact
string format = "ddMMyyyyHHmm";
DateTime dt = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);
or TryParseExact:
DateTime dt;
bool success = DateTime.TryParseExact(value, format,
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
The latter call will simply return false on parse failure, instead of throwing an exception - if you may have bad data which shouldn't cause the overall task to fail (e.g. it's user input, and you just want to prompt them) then this is a better call to use.
EDIT: For more details about the format string details, see "Custom Date and Time Format Strings" in MSDN.
You could use:
DateTime dt = DateTime.ParseExact(
date,
"ddMMyyyyHHmm",
CultureInfo.InvariantCulture);
string iDate = "05/05/2005";
DateTime oDate = Convert.ToDateTime(iDate);
DateTime oDate = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt",null);
DateTime Formats

Converting string dd/mm to datetime

Converting a String to DateTime
As the above link says I can do conversion if I'm having a the complete dd/mm/yyyy,But I'm having only dd/mm not the year field.
I have achieve it by changing the date to mm/dd format and using Convert.ToDateTime(date).So any help please.
You can parse that string. Just remember that the Month part is MM not mm (minutes)
string data = "01/01";
DateTime dt;
DateTime.TryParseExact(data, "dd/MM", CultureInfo.CurrentCulture, DateTimeStyles.None, out dt);
Console.WriteLine(dt.ToLongDateString());
Of course the missing year is assumed to be the current year
You can use this source to learn more about specifiers for parsing custom date's.
Put your string variable instead of CustomDate field.
DateTime d = DateTime.ParseExact(CustomDate, "dd/MM",System.Globalization.CultureInfo.CurrentCulture);
I would use the function DateTime.TryParseExact since you can use it within an If - else structure very easily
private DateTime date;
private myString = "23/04";
if (DateTime.TryParseExact(myString, "dd/MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
myDate = date;
}
else
{
//do nothing
}
With this you can catch errors when parsing the string.

How do I convert a DateTime variable to return date in the 'mm/dd/yy' format

private DateTime OrderDate;
OrderDate = Convert.ToDateTime("05/20/15")
How do I assign the above OrderDate variable a value of 05/20/15.
I tried using Convert.ToDateTime, but it seems to work for yyyy format but not yy.
You will want to create a new date time object and assign it to the property.
OrderDate = new DateTime(2015, 5, 20);
To assign it, you would use OrderDate = new DateTime(2015, 5, 20);
When displaying the value the .Net Framework will use the local culture or your machine.
If you want to use a different display format, (without changing the culture) you can use String.Format("{0:MM/dd/yy}", OrderDate)
You can't, Unless you change the date string to the correct format, it cannot guess which millennium you are reffering.
or you can take each part of the date sepretly and pass it in the constructor:
OrderDate = new DateTime(2015, 5, 20);
You can use DateTime.ParseExact to achieve this
DateTime OrderDate = DateTime.ParseExact("05/20/15", "MM/dd/yy", CultureInfo.InvariantCulture);
I would use DateTime.TryParseExact:
DateTime time;
if (DateTime.TryParseExact("05/20/15", "MM/dd/yy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out time))
{
do something ...
}
Lots of info about converting/formatting dates you can find here:
https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx
I guess in particular you need this example:
MSDN snippet:
public class Example
{
public static void Main()
{
string[] dateValues = { "30-12-2011", "12-30-2011",
"30-12-11", "12-30-11" };
string pattern = "MM-dd-yy";
DateTime parsedDate;
foreach (var dateValue in dateValues) {
if (DateTime.TryParseExact(dateValue, pattern, null,
DateTimeStyles.None, out parsedDate))
Console.WriteLine("Converted '{0}' to {1:d}.",
dateValue, parsedDate);
else
Console.WriteLine("Unable to convert '{0}' to a date and time.",
dateValue);
}
}
}
// The example displays the following output:
// Unable to convert '30-12-2011' to a date and time.
// Unable to convert '12-30-2011' to a date and time.
// Unable to convert '30-12-11' to a date and time.
// Converted '12-30-11' to 12/30/2011.

Converting System Date Format to Date Format Acceptable to DateTime in C#

How can I convert a system date format (like 3/18/2014) to the format readable in DateTime?
I wanted to get the total days from two dates, which will come from two TextBoxes.
I have tried this syntax:
DateTime tempDateBorrowed = DateTime.Parse(txtDateBorrowed.Text);
DateTime tempReturnDate = DateTime.Parse(txtReturnDate.Text);
TimeSpan span = DateTime.Today - tempDateBorrowed;
rf.txtDaysBorrowed.Text = span.ToString();
But tempDateBorrowed always returns the minimum date for a DateTime varibale. I think this is because DateTime does not properly parse my system date format. As a consequence, it incorrectly displays the number of days. For example, if I try to enter 3/17/2014 and 3/18/2014 respectively, I always get -365241 days instead of 1.
Edit: I wanted my locale to be non-specific so I did not set a specific locale for my date format. (My system format by the way is en-US)
Try DateTime.ParseExact method instead.
See following sample code (I've used strings instead of TextBoxes since I used a Console app to write this code). Hope this helps.
class Program
{
static void Main(string[] args)
{
string txtDateBorrowed = "3/17/2014";
string txtReturnDate = "3/18/2014";
string txtDaysBorrowed = string.Empty;
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed, "M/d/yyyy", null);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate, "M/d/yyyy", null);
TimeSpan span = DateTime.Today - tempDateBorrowed;
txtDaysBorrowed = span.ToString();
}
}
ToString is not Days
TimeSpan.TotalDays Property
You can try specifying the format of the datetime in the textboxes like this
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
Also you may have to check if the values from the textboxes are valid.
My first thought is to just replace the TextBox controls with a DateTimePicker or equivalent, depending on what platform you're developing on. Converting strings to dates or vice-versa is more of a pain than it seems at first.
Or you could try using DateTime.ParseExact instead, to specify the exact expected format:
DateTime tempDateBorrowed =
DateTime.ParseExact("3/17/2014", "M/dd/yyyy", CultureInfo.InvariantCulture);
Or you could specify a specific culture in the call to DateTime.Parse:
var tempDateBorrowed = DateTime.Parse("17/3/2014", new CultureInfo("en-gb"));
var tempDateBorrowed = DateTime.Parse("3/17/2014", new CultureInfo("en-us"));
try formatting your date to iso 8601 or something like that before parsing it with DateTime.Parse.
2014-03-17T00:00:00 should work with DateTime.Parse. ("yyyy-MM-ddTHH:mm:ssZ")
Try this:
if(DateTime.TryParseExact(txtDateBorrowed.Text, "M/d/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDateBorrowed))
{
TimeSpan span = DateTime.Today - tempDateBorrowed;
}

Why DateTime.TryParse returning false when given a real year string?

In the code below I am giving the function a sTransactionDate="1999" and I am trying to covert it to a date x/x/1999.
DateTime dTransactionDate = new DateTime();
if(DateTime.TryParse(sTransactionDate, out dTransactionDate))
{ //Happy
}else
{ //Sad
}
if the string is "1999" it will always end up in sad. Any ideas?
Try something like this (adjust the CultureInfo and DateTimeStyles appropriately):
DateTime.TryParseExact
("1999",
"yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dTransactionDate)
How about...
DateTime dTransactionDate = new DateTime();
if (DateTime.TryParseExact(sTransactionDate, "yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dTransactionDate))
{
// Happy
}
else
{
// Sad
}
...or even just...
DateTime dTransactionDate = new DateTime(int.Parse(sTransactionDate), 1, 1);
// Happy
"1999" is not a date, it's a year
try 1/1/1999
Also verify on a system calendar that the date you are attempting to parse existed. Just like you'll find "2/29/1949" is also going to return false because it never existed on the calendar.

Categories