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.
Related
I'm developing an application in which I pass one URL on inquiry.aspx page and that URL will send a message to the user's email address.
That URL looks like:
mail.Body += string.Format("<a href=\"http://www.abc.co.in/Download.aspx?period="
+ DateTime.Now.ToString("dd-MM-yyyy hh mm")
+ "&ProductName=" + productName + "\">Demo Download</a>");
Now I'm retrieving this to the pageload event of download.aspx page. My code is:
string PName = Request.QueryString["ProductName"] as string;
string myDate = Request.QueryString["period"] as string;
DateTime dt1 = Convert.ToDateTime(myDate);
DateTime dt2 = DateTime.Now;
int day1, day2;
day1 = dt1.Day;
day2 = dt2.Day;
TimeSpan variable = dt2 - dt1;
if (day1!=day2)
{
//Response.Write("Download time is expired now");
lblmsg.Visible = true;
lblmsg.Text = "Download time is expired now";
}
else
{
lblmsg.Visible = true;
lblmsg.Text = "U can Still Download";
}
I'm getting the error:
String was not recognized as a valid DateTime
My output URL after user clicking on that link from his email id looks like:
http://www.abc.co.in/Download.aspx?period=11-04-2013%2006%2036&ProductName=Otja
Here datetime is used for condition that after same day means mail is send to user today and today only he can download. Tommorrow onward it will show message that you are not able to download software now. So that is the reason to pass datetime on URL, but I'm getting error. Please someone help me it's required badly.
Couple of things you can try.
first and foremost change your Date format to Universal Date format and not regional. Assume you are using .net web application, I have seen issues where client execution is different for server.
yyyy-MM-dd
secondly, your datetime format string is not quite right, i.e. missing colon between hour and min. Also if you are trying the said format you must specify your TT or 24 hour. At the end of the say your format would look as follows
yyyy-MM-dd hh:mm tt
or
yyyy-MM-dd HH:mm
in addition the above you may want to use date -compare
DateTime dt1 = Convert.ToDateTime(myDate).Date;
DateTime dt2 = DateTime.Now.Date;
if(dt1 != dt2)
{
//...
}
else
{
//...
}
Since you are using DateTime.ToString("dd-MM-yyyy hh mm") when creating the URL, you should use the same format string when parsing it:
DateTime dt1 = DateTime.ParseExact(myDate, "dd-MM-yyyy hh mm", System.Globalization.CultureInfo.InvariantCulture);
Best practice requires you to also pass the culture when creating the URL:
DateTime.ToString("dd-MM-yyyy hh mm", CultureInfo.InvariantCulture).
By the way, you should not pass the date in URL in your code sample. Instead you would store the date together with a token in database and pass that token instead. Alternatively you could encrypt the date. The problem is that the recipient is able to change the date and thus overriding your checks for download availability.
I know this question has been asked before and resolved using various methods.
I am converting a value from a string to a DateTime.
Throughout the project I have used the same CultureInfo, all strings that where converted to date where done using Convert.ToDateTime(), but now there is one text field that refuses to convert.
I have tried:
string date = "27/02/2013";
string startdated = (Convert.ToDateTime(date)).ToString("yyyy/MM/dd");
(converts to datetime and changes it back to sting in my required format. This works fine on everything else)
even
Datetime dt = Convert.toDateTime(date); doesn't work
DateTime.ParseExact(date, "yyyy/MM/dd", format); doesn't work
And all give me the same error "String was not recognized as a valid DateTime.". i receive my date value from a textbox with an ajax calender extender (CalendarExtender.Format = "dd/MM/yyyy" done for display purposes,this also works everywhere else i.e "dd/MM/yyyy" for display and "yyyy/MM/dd" for procedure) except this final value which simply will not change. Everthing is done via my machine with no external servers
Your input string is not in the same format as the format you provde DateTime.ParseExact with.
For this to work
DateTime.ParseExact(date, "yyyy/MM/dd", format);
You have to enter the date in year/month/day format. But your string is in day/month/year.
This should work better.
string date = "27/02/2013";
DateTime parsedDate = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Your date is date = "27/02/2013"; and your current format (in DateTime.ParseExact) is "yyyy/MM/dd", It should be:
"dd/MM/yyyy"
So the following code should work.
string date = "27/02/2013";
DateTime dt = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
You can also use the format "d/M/yyyy" which would take care of single or double digit date/month.
I'm making a program using C# vs2008, this is a preparation for my thesis. I'm trying to make my date time picker to show month/day/year without the time in my datagridview. My date time picker is set into datetime.
Here's the sample of my code:
Registrar.InsertStudent(
Convert.ToInt32(txtStud_ID.Text),
txtFname.Text,
txtGname.Text,
txtMname.Text,
txtPAdd.Text,
txtLline.Text,
txtMobile.Text,
cbCitizen.SelectedItem.ToString(),
dtpDOB.Value,
Convert.ToInt32(txtAge.Text),
cbGradeLvL.SelectedItem.ToString(),
cbGender.SelectedItem.ToString(),
txtMotherName.Text,
txtMComp.Text,
txtMOcc.Text,
txtMAdd.Text,
txtMTele.Text,
txtFatherName.Text,
txtFComp.Text,
txtFOcc.Text,
txtFAdd.Text,
txtFTele.Text,
Convert.ToInt32(txtSiblings.Text),
txtSchool_Last_Attend.Text,
txtSchool_Add.Text,
txtDname.Text,
txtDTele.Text,
txtInsuComp.Text,
cbMedical_List.SelectedItem.ToString(),
txtPerson_Notified.Text,
cbRelation_Pupil.SelectedItem.ToString(),
txtIE_Contact.Text,
txtOther_Allergy.Text,
txtOtherIE.Text
);
You can set custom date format to the DateTimePicker as follows:
this.datetimepicker.Format = DateTimePickerFormat.Custom;
this.datetimepicker.CustomFormat = "MM-dd-yyyy"
You can try with this code
var result = dateTimePicker1.Value.Date.ToString();
Don't fully understand your question but if you can access the DateTime variable.
DateTime dt = DateTime.Now;
string dateString = dt.ToString("yyyy-mm-dd");
dateString now equals = "2012-09-08" (depending on timezone)
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);
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