DateTime Error in URL - c#

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.

Related

DateTime Parse from PDT

I have a string which contains a date as shown below
string dateTime = "18-Aug-2016 12:02:44 AM PDT";
I want it to be converted to the below format
Output = 2016-08-18T00:02:44-07:00
I tried the below code, but still I need to modify it to get my required output
string mydate = dateTime.Replace("PDT", "-0700");
DateTime dt = Convert.ToDateTime(mydate);
string dateTime = "18-Aug-2016 12:02:44 AM PDT";
string mydate = dateTime.Replace("PDT", "-0700");
DateTime dt = Convert.ToDateTime(mydate);
Console.WriteLine("The current date and time: {0:O}", dt);
Gives me the following output:
The current date and time: 2016-08-18T09:02:44.0000000+02:00
Not sure if PDT is globally unique, nor if that zone changes during daylight savings time.
Id report back to the Google server team that they are returning something "interesting"

Get yesterday's date from the date entered

I have console application that accepts date as parameter. However, the date is passed as a string in this format:
string dt = DateTime.Now.ToString("yyyyMMdd");
Once the date is entered I need to programmatically get day - 1 from the entered date. Since this is a string, I cannot do any calculation.
For example, user enters:
20141023
I need to subtract a day from the date to get:
20141022
I did a quick fix to solve my immediate need, however, this is not the right way to do it and it has a bug:
int yt = Int32.Parse(dt) - 1;
And then I turn around and convert it yt.ToString()
The above solution will not work if it's the 1st of the month.
Is there a way I can programmatically get yesterday's date in the format (yyyyMMdd) without changing the format and possibly not using the TimeSpan?
Why don't parse the input into a DateTime object? Then you can use the DateTime.AddDays(-1)
For example:
var inputDate = DateTime.ParseExact("20141022", "yyyyMMdd", CultureInfo.InvariantCulture); // change "20141022" into the inputted value
var yesterday = inputDate.AddDays(-1);
var yesterdayString = yesterday.ToString("yyyyMMdd"); // this will be yesterdays date, in the string format
Try this...
DateTime data = DateTime.ParseExact("20141023", "yyyyMMdd", CultureInfo.InvariantCulture);
Console.WriteLine("{0} - {1}", data, data.AddDays(-1).ToString("yyyyMMdd"));
Would this work for you ?
string newDateTimeStr = (DateTime.Today.AddDays(-1)).ToString("yyyyMMdd");
EDIT:
for the date entered by the user:
string txtInputDate = Console.ReadLine();
DateTime dateTime = new DateTime(txtInputDate).ToLocalTime();
string newDateTimeStr = (dateTime.AddDays(-1)).ToString("yyyyMMdd");

Datetime format problems in iis Asp.net

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.

Getting Null value on parameter in querystring parameter

in my application i have send one link to User's email id he can download software on clicking this link....now my url is look like....
http://www.abc.co.in/Download.aspx?period=11/04/2013%2012:29:20%20PM&ProductName=Otja
and my code for retriving this value on pageload download.aspx page is
string PName = Request.QueryString["ProductName"] as string;
string myDate = Request.QueryString["period"];
if (!String.IsNullOrEmpty(myDate))
{
myDate = myDate.Replace("!", ":");
}
DateTime dt1 = Convert.ToDateTime(myDate);
DateTime dt2 = DateTime.Now;
TimeSpan variable = dt2 - dt1;
if (variable.TotalMinutes > 5)
{
//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";
}
but this is not working i tested and before 5 Minute and after minutes it is only shows "You can still download" so i think my error is that i can not retrive that productname and period value on querystring on this download.aspx page..please help me.. thanks
i think there should be error..... String was not recognized as a valid DateTime. thats why it is pass null value so any solution ???
You said you think that your code is not able to retrieve the query params. Why don't you confirm that by printing the values first.
The Request.QueryString() looks correct.
There could be issue with your logic which may case the else to execute.
Based on more information provided by you please try this -
Variable myDate value must be “11-04-2013 06 36”. Please confirm.
Instead of Convert.ToDateTime(myDate); try this
DateTime.ParseExact(myDate, "dd-MM-yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture);

Error while converting string to DateTime after publishing to web server

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);

Categories

Resources