开发者

Watin : Get Datetime and perform calculation

开发者 https://www.devze.com 2023-02-14 02:31 出处:网络
I have a textfield that has a date with the format \"12/23/2010\".Is the开发者_如何转开发re away for me to get the number 23 using watin ie get number from textfield;i\'m gonna use it like this.

I have a textfield that has a date with the format "12/23/2010".Is the开发者_如何转开发re away for me to get the number 23 using watin ie get number from textfield;i'm gonna use it like this.

1.Get datetime 12/23/2010 and get number '23' 
2.substract 2 from 23 and store it somewhere[ie: 23 - 2 = 21] 
3.Insert the new datetime number [ie:12/21/2010 ]

string myDate = browser.TextField(Find.ByName("myTextField")).Value;
DateTime time =  = new DateTime();
time2 = time - 2;
browser.TextField(Find.ByName("myTextField")).TypeText(time2);

Is this possible?or should i be looking to another way.Ask the user to insert the data instead.


You should use DateTime.Parse, DateTime.TryParse, DateTime.ParseExact or DateTime.TryParseExact to parse from text to a DateTime.

If a failure to parse indicates a failure in the code somewhere (which is probably the case here, given that it's a test) I suspect DateTime.ParseExact is the most appropriate approach, providing the expected format, culture etc.


if what you want is to subtract 2 days from a date I would do it like this:

DateTime dt = DateTime.Parse(myDate)-TimeSpan.FromDays(2); 
//its steps 1,2 & 3 in one easy to read line :)

This is of course if you are sure the string you have IS a valid date. If it might not be, then you should do what the Skeet recommends, which is using first a try parse, checking if the return value is true, and if it is, then do the rest, and if it is not, send an error message.


consider writing

DateTime dt = Convert.ToDateTime(myDate);
DateTime dtNew = new DateTime(dt.Year, dt.Month, dt.Day - 2);
browser.TextField(Find.ByName("myTextField")).TypeText(dtNew.ToShortDateString());


Try getting the value of the date as string Convert it to datetime and use AddDays we can use negative or positive value And insert it into textbox

string myDate = this.Elements.textfield.Value;
DateTime dt = Convert.ToDateTime(myDate);
DateTime dtNew = dt.AddDays(-3);
this.Elements.ChangeDateActive.TypeText(dtNew.ToShortDateString());

That's it thanks

0

精彩评论

暂无评论...
验证码 换一张
取 消