in C# I'm trying to do a DateTime.TryParse on a string field which I am getting from a DataFeed which I know is in "MM/dd/YYYY" format. e.g.
DateTime dt = DateTime.TryParse("01/30/11");
Only thing is now "dt" is in the incorrect format to be stored into my Database which has a DateTime locale setting of "dd/MM/YYYY".
How do I go about parsing the string field correctly into dt and then into my DB? What would be the best way to handle this? If I set the globalization of my CurrentThread to en-US, then dt would be in en-US format, however when inserting into the DB, it is still incorrectly stored? :S
Thanks
David
Use the DateTime.ParseExact method:
DateTime dt = DateTime.ParseExact("15/12/2011", "dd/MM/yyyy", CultureInfo.InvariantCulture);
If you want to convert the DateTime value to a string back, use the following code:
string dtString = string.Format("{0: dd/MM/yyyy}", dt);
Try using TryParseExact.
http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx
I hope you understand, the TryParse be made by the if statement, see the following example,
private void button1_Click_1(object sender, EventArgs e)
{
DateTime myData = new DateTime();
if (DateTime.TryParse(this.textBox1.Text,out myData))
{
// your filed db = myData
}
}
you then enter in the block if the update of the database field, according to the cultures set on your PC.
Bye
Related
I want to compare database datetime value that is stored in dd/mm/yyyy format, with the textbox value that is stored in dd-mmm-yyyy format.
I have tired converting the database value to dd-mmm-yyyy format using parseexact-
DateTime dtdb = DateTime.ParseExact(dr["paydate"].ToString(), "dd-MMM-yyyy",null);
and then comparing with the textbox value,
if(dtdb.ToString() != txtpaydate.Text)
But its giving me this error:
String was not recognized as a valid DateTime.
I also tried doing this:
Convert.ToDateTime(dr["paydate"]).ToString("dd-MMM-yyyy")!= txtpaydate.text
but its still giving me the same error. Please let me know how can I solve this issue. Thank you.
you can convert DateTime value and textbox DateTime value to timestamp (from 1970-0-0) then compare it
edited
maybe you want to read rfc3389 about timestamp
You need to parse your textbox into DateTime object and than you can completely free to use general arithmetic operations such as:
if (dtdb > dttb) and etc. If you have any trouble for parsing it, check this page for further information.
If there's any more question, feel free to ask here. But please check stackoverflow before. Have a great day.
string dtdb =dr["paydate"].ToString("dd-MMM-yyyy");
var dt=txtpaydate.Text.ToString("dd-MMM-yyyy");
if(dtdb!= dt)
{
//do what you want
}
As said, it's best to manipulate pure DateTime objects.
You can do it this way:
// Example strings
var myDate1AsString = "31/12/2016";
var myDate2AsString = "31-dec-2016";
// DateTime object used to retrieved the dates as string
var myDate1AsDate = new DateTime();
var myDate2AsDate = new DateTime();
// Parse the strings; if the parse fail, the date is set to DateTime.MinValue
DateTime.TryParseExact(myDate1AsString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate1AsDate);
DateTime.TryParseExact(myDate2AsString, "dd-MMM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate2AsDate);
// Correctly compare the dates
var result = DateTime.Compare(myDate1AsDate, myDate2AsDate);
// or, directly compare a date with the other.
if (!myDate1AsDate.Equals(myDate2AsDate))
{
// Do some stuff.
}
Always use a CultureInfo when parsing date.
Worked with phpMyAdmin, and wanted to update data from C#.
I had "yyyy-MM-dd" format for column dateBuy in phpMyAdmin.
To display it, I changed the format to "dd/MM/yyyy" in C#.
This is the code: (I don't have problem with this code)
string dateBuy = dr.GetValue(1).ToString();
DateTime time = DateTime.Parse(dateBuy);
dateBuy = time.ToString("dd/MM/yyyy");
To update database, I wanted to change the format back to "yyyy-MM-dd". But, I had an error: "String was not recognized as a valid DateTime".
This is the error parts of my code:
string dateBuy2 = txtDateBuy.Text;
dateBuy = (DateTime.ParseExact(dateBuy2, "yyyy-MM-dd", null)).ToString();
Did I make mistake in the DateTime syntax? Thanks for your help.
[Since it is not good if we continue in the comments (the comments will be long), I will just put up what I think as a solution here]
To format dateBuy to the format that you want, you should also put the string format in the ToString()
That is, instead of
dateBuy = (DateTime.ParseExact(dateBuy2, "yyyy-MM-dd", null)).ToString();
put
dateBuy = (DateTime.ParseExact(dateBuy2, "yyyy-MM-dd", null)).ToString("yyyy-MM-dd");
Otherwise, it is possible for the ToString() to produce something like "2015-10-16 12:00:00 AM" instead of "2015-10-16"
However, since you use ParseExact, the input for the dateBuy2 must also be in the format of "yyyy-MM-dd" which defeats the purpose. You may consider using DateTimePicker such that you can control the input format.
Alternatively, you can use DateTime.Parse or TryParse (as suggested by Martheen) instead, something like this
try {
DateTime dt = DateTime.Parse(txtDateBuy.Text);
dateBuy = dt.ToString("yyyy-MM-dd");
} catch (Exception exc) {
//wrong format, do something to tell the user
}
If input has to be in the TextBox you better put try-catch to prevent your program crash for taking wrong-formatted input if you use Parse.
Where as if you use TryParseyou can put it in if-else block statement instead
DateTime dt;
if (DateTime.TryParse(txtDateBuy.Text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out dt)) {
//correct format, do something using dt
} else {
//incorrect format, warns the user
}
To get CultureInfo enum you need to add reference to System.Globalization
[Edited after suggestion given by Mr. Soner Gonul]
Hi I am trying to convert a string to date time and then back to a string. This is my code.
try
{
string dt = "19/9/13";
DateTime.Parse(dt.ToString()).ToString("yyyy-MM-dd");
}
catch (Exception ex)
{
string msg = ex.Message;
}
and also tried Convert.ToDateTime(dt.ToString()).ToString("yyyy-MM-dd");
I am getting this error String was not recognized as a valid DateTime.. can any one give a solution.
I don't know what culture you are using, however, by default it's date-separator is used. So if you for example use . as separator that won't work.
Use CultureInfo.InvariantCulture and DateTime.ParseExact:
DateTime dt DateTime.ParseExact("19/9/13", "dd/M/yyyy", CultureInfo.InvariantCulture);
string result = dt.ToString("yyyy-MM-dd");
Here you have:
string time = "19/9/13";
DateTime resds =DateTime.ParseExact(time, "dd/M/yy", System.Globalization.CultureInfo.InvariantCulture);
string datet = resds.ToShortDateString();
DateTime.ParseExact documentation
Your parsing is true. The problem is the datetime because your computer supports another datetime format. It tries to get 19 as a month - and it throws this exception.
Probably if you write this it will work:
string dt = "9/19/13";
Or just change your computer settings to: dd/MMM/YYYY format.
try with DateTime.ParseExact :
DateTime.ParseExact(dt.ToString(), "dd/M/yy", null).ToString("yyyy-MM-dd");
You should use DateTime.ParseExact:
DateTime.ParseExact(dt, "dd/M/yy").ToString("yyyy-MM-dd");
And take a look at Custom Date and Time Format Strings.
Use Convert.ToDateTime() to convert string into date.. and then date to string use ToString()
string dt = "19/9/13";
Convert.ToDateTime(dt);
I have got two TextBoxes(txtdateofissue and txtdateofexpiry).The First Textbox is Attached with a CalendarExtender control.
I want that if a user selects a date for the txtdateofissue textbox then automatically the same date but next year should get entered in txtdateofexpiry textbox.
Date Should be in dd-MM-yyyy format i.e. 24-04-2013.
i have written a code for this but i am getting an error (String is not a valid datetime format)
my code:
protected void txtdateofIssue_TextChanged(object sender, EventArgs e)
{
DateTime dt = Convert.ToDateTime(txtdateofIssue.Text);
dt = dt.AddDays(-1).AddYears(1);
txtdateofExpiry.Text = dt.ToShortDateString();
}
the first line in which i declare datetime variable dt throws up the error (String is not a valid datetime format)
when i run this code in my local machine it works fine but if i run it on iis then it shows errors...please either correct my code or guide me in a new way...thanks in advance...
you can use DateTime.TryParseExact method
DateTime dt;
if (DateTime.TryParseExact(txtdateofIssue.Text, "dd-MM-yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
dt = dt.AddDays(-1).AddYears(1);
txtdateofExpiry.Text = dt.ToString("dd-MM-yyyy");
}
To convert Date Time back to given format
Look at the docs for custom date and time format strings for more info.
I am using below code
DateTime dtt=new DateTime();
dtt = Convert.ToDateTime(FromDate);
// DateTime dtt = DateTime.Parse(FromDate); //this also gives the same error
con = new MySqlConnection(conString);
con.Open();
for (int i = 1; i <= TotalDays; i++)
{
string updateHotelBooking = "Update tbl_hotelbookingdetail set `BookedRoom`=`BookedRoom`+"+1+", `AvailableRoom`=`TotalRoom`-`BookedRoom` where `HotelID`="+HotelID+" AND `CurrentDate`='"+dtt.ToString("dd-MM-yyyy")+"'";
MySqlCommand cmd7=new MySqlCommand(updateHotelBooking,con);
cmd7.ExecuteNonQuery();
dtt = dtt.AddDays(1);
}
This code is in one of my webservice which I am using for iPhone application.
here FromDate is string with value in this formate 15-11-2011 which is coming from the application in string format. I am converting it to DateTime because in loop of total days
I need to add day to dtt.
It is working fine on local host with dtt value 15-11-2011 00:00:00
but when I published it,it gives error
String was not recognize as valid DateTime
This is almost certainly because your server uses a different culture by default - and your code is just using the current thread culture.
You can specify this using DateTime.Parse - or specify the pattern explicitly with DateTime.ParseExact or DateTime.TryParseExact - but we need to know more about where the string is coming from to suggest the best approach. Is it from the user? If so, you should use the user's culture to parse it. Is it a specific format (e.g. from an XML document) instead? If so, parse using that specific format.
Ideally, get rid of the string part entirely - if you're fetching it from a database for example, can you store it and fetch it as a DateTime instead of as a string? It's worth trying to reduce the number of string conversions involved as far as possible.
EDIT: To parse from a fixed format of dd-MM-yyyy I would use:
DateTime value;
if (DateTime.TryParseExact(text, "dd-MM-yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out value))
{
// Value will now be midnight UTC on the given date
}
else
{
// Parsing failed - invalid data
}
What are you culture settings on your local machine and on the server?
The DateTime conversion is dependent on the current culture - dates are written quite differently in different countries.
One way to make the conversion "predictible" is to use the invariant culture:
DateTime dtt = Convert.ToDateTime(FromDate, CultureInfo.InvariantCulture);
the server date format may be in mm/dd/yyyy and you are trying to pass dd/mm/yyyy
using System;
using System.Globalization;
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.
Check this for more details
Log (or otherwise provide feedback to yourself) what FromDate is. Maybe it's empty?
May the Language Settings on the Server are different so it does not recognize the dd-MM-yyyy - try using DateTime.ParseExact(dateString, "dd-MM-yyyy", CultureInfo.InvariantCulture);