how to convert server time to local time - asp.net

I have a problem with time
My server is in the USA and I'm in Denmark (Europa) and I would like to have my site show the time in my local time. How can I do that?
I try this
Datetime localtime = DateTimeOffset.Now.ToOffset(new TimeSpan(1,0,0)).DateTime;
and it works, but it will only work when I'm in GMT+1 / UTC+1 and not when I'm in GMT+2 / UTC+2.
Is there another way of doing this - a simpler way of doing it?

The only way you should do it is as follows:
string zoneId = "Central European Standard Time";
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
DateTime result = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow,tzi);
Console.WriteLine("Time is " + result + " in Denmark");
Using the TimeZoneInfo class is the only reliable way in .Net to convert to/from different timezones AND get proper DST conversions.
TimeZoneInfo.ConvertTimeToUtc(dtLocal,tzi) is the reverse converting from a local time to a utc time.
For the TimeZone Id strings, you can run the bit of code here...
foreach( var tz in TimeZoneInfo.GetSystemTimeZones() )
{
Console.WriteLine(tz.DisplayName + " is Id=','" + tz.Id + "'");
}

You can get the time off the server and do this.
DateTime myTimeGMT = ServerTime.ToUniversalTime();
This do this:
DateTime myTimeLocal = myTimeGMT.ToLocalTime();
The only restriction here is the computer you are on must be set to the time zone you are converting to.
In my experience, .NET has trouble converting between timezones when neither the 'From' time or the 'To' time are the local time zone.
I hope this helps.

I did the conversion to be displayed in a gridview using a template field.
<asp:TemplateField HeaderText="Last Activity">
<ItemTemplate>
<asp:Label ID="LastActivityLBL" runat="server" Text='<%# Convert.ToDateTime(Eval("LastActivityDate")).ToLocalTime() %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Login">
<ItemTemplate>
<asp:Label ID="LastLoginLBL" runat="server" Text='<%# Convert.ToDateTime(Eval("LastLoginDate")).ToLocalTime() %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

Datetime localtime = DateTimeOffset.Now.ToOffset(new TimeSpan(1,0,0)).DateTime;
You can change your TimeSpan like--
Datetime localtime = DateTimeOffset.Now.ToOffset(new TimeSpan(3,0,0)).DateTime;
according to the time zone.

Related

Input string was not in a correct format error when passing values of decimal data type as querystring

We have the following field names in our database with data type of decimal:
RentalFee
ExtraHourFee
CancelFee
KeyDeposit
When attempting to pass their values as querystring from one page to another, we run into Input string was not in a correct format error.
Here is a snippet of the markup:
<asp:TemplateField HeaderText="Select" SortExpression="siteid">
<ItemTemplate>
<asp:HyperLink ID="hdReserve" Text="Select" runat="server"
NavigateUrl='<%# "Reserve.aspx?id=" + Eval("siteId") + "&groupsize=" + ddlPartySize.SelectedValue + "&facilityFees= " + Eval("RentalFeeAmount") + "&facilityFees= " + Eval("RentalFeeAmount") + "&depoitAmt= " + Eval("DepositAmount") + "&cancelAmt= " + Eval("CancellationAmount") + "&keydeptAmt= " + Eval("KeyDepositAmount") %>' />
</ItemTemplate>
</asp:TemplateField>
Then the values are grabbed from codebehind:
Dim intRentalFee As Decimal
Dim intExtraHourFee As Decimal
Dim intCancelFee As Decimal
Dim intKeyDeposit As Decimal
rentalfeeHide.Text = Request.QueryString("facilityfees")
extrahrfeeHide.Text = Request.QueryString("extrahour")
cancelfeeHide.Text = Request.QueryString("cancelAmt")
keydepositfeeHide.Text = Request.QueryString("keydeptAmt")
intRentalFee = rentalfeeHide.Text
intExtraHourFee = extrahrfeeHide.Text
intCancelFee = cancelfeeHide.Text
intKeyDeposit = keydepositfeeHide.Text
' Add all up to get total fee
lblTotal.Text = intRentalFee + intExtraHourFee + intCancelFee + intKeyDeposit
Any ideas how to resolve this?
I would use the following instead as it is very difficult to see what is happening:
<asp:hyperlinkfield datatextfield="UnitPrice"
datanavigateurlfields="siteId,groupsize,facilityFees"
datanavigateurlformatstring="~/details.aspx?siteId={0}&groupsize={1}&facilityFees={2}" />
The above only demonstrates a few fields but it uses datanavigateurlformatstring for the url and datanavigateurlfields for the arguments which can be specified with a comma-separated string.
MSDN Hyperlink reference
You should then be able to clearly see in the url what the values are and check that they match your intended type for the destination page and convert them i.e.
var facilityfees = Convert.ToDecimal(Request.QueryString("facilityfees"));
Do in in code behind...
hdReserve.NavigateUrl = string.Format("../Reserve.aspx?id=?id={0}&groupsize={1}&facilityFees={2}...", siteId, ddlPartySize.SelectedValue, intExtraHourFee...)
In addition to Huchanoid's answer you need to make some mods to your codebehind.
First off you say the values are decimal but you are using them as integers? Which are they?
Next, what is the querystrings don't exists... someone just types in the page name... I would say you need to check that these values exist and then cast them as integers (or Decimal)... Use
If Not IsNothing(Request.QueryString("yourQueryStringName")) Then
'check that they are numeric or use a try catch...
If isNumeric(Request.QueryString("yourQueryStringName")) Then
'Querystring is Numeric
intYourQueryStringName = Cint(Request.QueryString("yourQueryStringName"))
Else
'Error Querystring is not numeric
Response.Redirect("Somwhere.aspx")
End If
Else
'QueryString does not exist
Response.Redirect("Somwhere.aspx")
End If

Date text field asp.net

Can anyone lead me in the right direction as to how to set a textbox such as this:
<td><asp:TextBox ID="txtBoxDate" runat="server" CssClass="fields"></asp:TextBox></td>
Into a masked text box that meets this style "mm/dd/yyyy"
Why not just simply convert the DateTime object to that format in server-side code?
Try this
DateTime dateTime = "your-date-time";
var asString = dateTime.ToString("mm/dd/yyyy");
asString will now have the format you've converted the DateTime object to. It will be string. So, after this step you can execute this
txtBoxDate.Text = asString;
..this might be the code you're looking for.

RangeValidator doesnt work as expected using specific date

When I try to submit a specific date "20-10-2013" (international format: 2013-10-20"), rangevalidator throws the error message for invalid date
<asp:TextBox ID="txtDataInicial" runat="server" Width="55px"></asp:TextBox>
<asp:RangeValidator ID="rgvDtInicial" runat="server" ControlToValidate="txtDataInicial"
Display="Static" MinimumValue="01/01/1800" MaximumValue="31/12/9999" Type="Date"
ErrorMessage="A data inicial, deve ter o seguinte formato: DD/MM/AAAA"
ValidationGroup="Consultar"></asp:RangeValidator>
<asp:Button ID="btnConsultar" runat="server" Style="width: 150px;" Text="Consultar"
OnClick="btnConsultar_Click" ValidationGroup="Consultar" />
It works for dates like , "19-10-2013", "21-10-2013", "20-10-2014", "20-10-2012".
It just happens when I submit this date!
Does anyone know why?
Dates are culture-depended. Specify your culture declaratively in web.config or in a Page directive, or programatically.
Check this out: http://msdn.microsoft.com/en-us/library/bz9tc508(v=vs.100).aspx
Rangevalidator control front end code
This is the culprit of the error. Make sure the cultureinvariantvalues is set to false.
Ensure assigning the correct minimum & maximum date range at code behind.
This is to standardise our date comparison to culture="en-GB" which use "dd/mm/yyyy" independent of server localization setting. You may use the "en-US" and the format will be "mm-dd-yyyy".
http://chinteongtan.blogspot.com/2014_04_01_archive.html

ASP.NET File Upload Validation

I have a requirement to do multiple validations on a file upload control. I have the following code for now:
<asp:Button id="btnUploadFile" class="ms-ButtonHeightWidth" runat="server" OnClick="UploadFile_Click" Text="Upload File"></asp:Button>
<asp:RequiredFieldValidator ID="InputFileValidator" ControlToValidate="InputFile" Text="You must specify a value for the required field" runat="server" />
I need to add this ^(?!..)(?!...)(?=.[^.]$)[^\"#%&:<>?\/{|}~]{1,128}$ Regex validation from here in addition to the required field validator. How do I do this?
UPDATE:
You could probably adapt the regex instead to allow for backslashes up to the filename and disallow them in the filename, but the complexity of such a beast would not likely be worth the time and effort to construct it.
Since the original regex was for validating a textbox where the user was typing a filename (and not a file input where the name is generated by the OS), I think the better course of action would be to use an <asp:CustomValidator> control instead and split the value on \ to get more easily parseable chunks.
The primary advantage of this approach is that you can break that complex regex down into multiple simpler (and more easily understood) regexes and test them one at a time against the filename.
<script type="text/javascript">
var validateFile = function validateFile(sender, args) {
'use strict';
var fileWithPath, //split on backslash
fileName = fileWithPath[fileWithPath.length - 1], //grab the last element
containsInvalidChars = /["#%&*:<>?\/{|}~]/g, //no reason to include \ as we split on that.
containsSequentialDots = /[.][.]+/g, //literal .. or ... or .... (etc.)
endsWithDot = /[.]$/g, // . at end of string
startsWithDot = /^[.]/g, // . at start of string
notValid = false, //boolean for flagging not valid
valid = fileName.length > 0 && fileName.length <= 128;
notValid = containsInvalidChars.test(fileName);
notValid = notValid || containsSequentialDots.test(fileName);
notValid = notValid || endsWithDot.test(fileName);
notValid = notValid || startsWithDot.test(fileName);
args.IsValid = valid && !notValid;
};
</script>
<asp:FileUpload ID="InputFile" runat="server" />
<asp:RequiredFieldValidator ID="rqfvInputFile" runat="server" ControlToValidate="InputFile" ErrorMessage="File is required"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="cstvInputFile" runat="server" ControlToValidate="InputFile" ClientValidationFunction="validateFile" ErrorMessage="File is not a sharepoint file"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" />
One caveat to the above is that the filename chunks are split on \, which is not likely to be the path separator for Unix or Mac systems. If you need this to run on those clients as well, you'll likely have to split on either \ or / which you should be able to do with this:
var filePath = args.Value.split(/\\|\//g); //not tested.
ORIGINAL:
Add in an <asp:RegularExpressionValidator> control and set the ControlToValidate property to your file uploader control.
You can have as many validator controls as you like pointed towards a single input.
Just set the appropriate properties (such as the ValidationExpression in the <asp:RegularExpressionValidator>) and make sure the ControlToValidate property is pointed towards the input to validate.
Example:
<asp:Button id="btnUploadFile" class="ms-ButtonHeightWidth" runat="server" OnClick="UploadFile_Click" Text="Upload File"></asp:Button>
<asp:RequiredFieldValidator runat="server" ID="RequiredInputFileValidator" ControlToValidate="InputFile" Text="You must specify a value for the required field" />
<asp:RegularExpressionValidator runat="server" ID="RegexInputFileValidator" ControlToValidate="InputFile" ErrorMessage="Only valid SharePoint files are allowed."
ValidationExpression="^(?!..)(?!...)(?=.[^.]$)[^\"#%&:<>?\/{|}~]{1,128}$" />
You may also want to look into Validation groups

Convert time to decimals in .net

Is there an easy way to present time (hh:mm) as a decimal value?
Example, 01:08 should become 1,13.
I have an asp:textbox masked (ajax) as time with the mask format "99:99". Next to this box I need to present the entered value as decimal.
<asp:TextBox ID="time" runat="server" /> hh:mm ([time in decimal format])
<ajaxToolkit:MaskedEditExtender runat="server" Mask="99:99" TargetControlID="time" MaskType="Time" />
You can use the TotalHours property of the TimeSpan, like this:
DateTime endHour = new DateTime(2010, 1, 2, 5, 30, 0);
double totalHours = new TimeSpan(endHour.Hour, endHour.Minute, 0).TotalHours;
First up, you might find it more appropriate to use a TimeSpan rather than a DateTime. So for your example, this:
TimeSpan t = new TimeSpan(0, 1, 8);
decimal d = t.Minutes + (t.Seconds / 60m);
Console.WriteLine(d.ToString());
produces the correct result. The m after the 60 forces that calculation to be decimal.
You can't hook this C# directly to the onblur of the textbox, as it runs server side. If you need this to run client side you will have to either use an ajax callback to evaluate it, or use javascript to cut the string up, then calculate each bit (minutes and seconds) individually, then output the result to the second textbox or label.
double decimalTime = DateTime.Now.Hour + (double)DateTime.Now.Minute/60
Edit: Better way, using GenEric's TimeSpan idea:
double hours = new TimeSpan(DateTime.Now.Hour,
DateTime.Now.Minute,
0).TotalHours;
(CDate("01:08").TimeOfDay.TotalHours).ToString("N2"))

Resources