I am using datepicker in xamarin forms but it shows date format by defualt "MM/dd/yyyy" and i have changed it to "dd/MM/yyyy" but when i bind the datepicker with viewmodel on save command then it changed to "MM/dd/yyyy" on my model and my model date property is in string type. also when i pass any string date from database to datepicker it does not change the date in this i have to convert date to again "MM/dd/yyyy", I want to ask is their any solution to format datepicker to parmanent to "dd/MM/yyyy" because i want to save and show date in "dd/MM/yyyy" format.
Thanks u in advance.
Try to use this method. Date format displaying depends on the current culture in your app. Set current culture globally by using this method inside App.xaml.cs.
Also take a look at DateTimeFormatInfo property in your cultureInfo object
using System.Globalization;
using System.Threading;
private void SetCultureToUSEnglish()
{
CultureInfo englishUSCulture = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = englishUSCulture;
}
Related
I need to validate a date field which is being entered by a user via a visualforce page.
The format my code expects is "yyyy-MM-dd".
What is the best way to handle this in apex. I have done similar stuff in Java before using certain standard classes which are not available in Apex like SimpleDateFormat for example.
Now I can check if the "format" is correct using a regular expression. But I must also prevent users from entering "9999-99-99" which satisfies the format. I am hoping Salesforce has a good built-in solution.
Thanks,
Calvin
You might try what I call control spoofing. I basically create an empty sObject that has a date field like a Task object (or something similarly light weight). On the screen I display the input for the task date which will render the native date field. Doing this you get salesforce to validate the date input from the user, and the user get's the nice calendar popup as well.
Here is a sample of what that would look like in the controller
public class MyController {
public Task DateInput {get;set;}
public MyController() {
DateInput = new Task();
}
public void save() {
Date dInputDate = DateInput.ActivityDate;
//Format Date
DateTime dtValue = DateTime.newInstance(dInputDate.year(), dInputDate.month(), dInputDate.day());
string sFormattedDate = dtValue.format('yyyy-MM-dd');
}
}
Here is what the Page would look like
<apex:page controller="MyController">
<apex:form>
<apex:pageBlock>
<apex:pageBlockSection>
<apex:pageBlockSectionItem>
<apex:outputLabel for="inputDate" value="My Date"/>
<apex:inputField value="{!DateInput.ActivityDate}" />
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
You notice the formatting that I did in the save method. You can't use format on Date but you can on DateTime so I just convert the Date to a DateTime and then use the format method to format my date.
Guys I managed to solve my problem because it was a little unique anyways.
So I used a regex to validate the format of the date being entered to ensure it is in yyyy-MM-dd format.
The I used Date.valueOf
This built in method always takes a date in the form of yyyy-MM-dd. It throws an exception if that has a bad value like 9999-99-99 etc....I display the exception's message to the user using e.getMessage() to complete my validation of the date fields.
In all my projects, I have jQuery date pickers that format the date dd-MMM-yyyy
which both users worldwide and the DateTime.parse method understand perfectly - sadly this does not appear to be the case for data annotation validation! I have my data annotation as below:
[Display(Name = "Date of Birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d-MMM-yyyy}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "You must enter a date of birth.")]
public DateTime dob { get; set; }
And my form refuses to submit with the error as below:
Does anyone know how I can make it validate, accept and modelbind a date value in this format?
You could write a custom model binder for the DateTime type as I have shown here that will use the format defined in the [DisplayFormat] attribute when parsing back a DateTime field from the request. By the default the model binder uses the CultureInfo setting of the current thread or the value you have configured in the <globalization> element of your web.config. If you set it to auto, then ASP.NET will use the client Accept-Language request header to adjust the culture info.
I'm a newbie to MVC 3 and JQuery Validation so any help I can get here will be very much appreciated.
My devleopment platform is .NET MVC 3 website. I'm using the built in unobtrusive javascript for form validation. Is there a way to change the date to a different format for a valid date. As far as I can tell, the valid format is dd/mm/yy. Is it possible to change the valid date format to something like "Apr 3, 2012"?
My view model has a field
[Required]
DateTime OrderDate { get; set; }
I know that MVC 3 is using jquery validation under the hood so I'm thinking the solution will require a change to jquery validate and also not sure how to hook it up to MVC so it works like all the other built in data validations using data annotations.
Thank you.
When you use client side validation for date, you have to override the jQuery validation for date as well.
$.validator.methods.date = function (value, element) {
return this.optional(element) || Globalize.parseDate(value, "MMM dd, yyyy") !== null;
}
You have to reference the Globalize library and the appropriate culture in your HTML head. Download from https://github.com/jquery/globalize.
If you wanted to change the format of Order Date you would do so with the DisplayFormat annotation:
[DisplayName("Order Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yy}")]
[Required]
DateTime OrderDate { get; set; }
Where the DataFormatString is your desired date time format.
My application is setted with pt-BR culture (Date is dd-mm-yyyy) in web.config:
<globalization enableClientBasedCulture="false" requestEncoding="utf-8" responseEncoding="utf-8" fileEncoding="iso-8859-15" responseHeaderEncoding="utf-8" resourceProviderFactoryType="string" enableBestFitResponseEncoding="true" culture="pt-BR" uiCulture="pt-BR" />
All DateTime created on my system is in right format, but I created a controller method like that:
public ActionResult Test(DateTime date)
{
}
Calling that method direct in the browser is passing null when the date is with portuguese-br format, like that:
mysite/Test/?date=19/01/2012 => date = null in my controller
mysite/Test/?date=01/01/2012 => date is fine, but in US format (mm-dd-yyyy)
How can I fix that, to accept my date format?
There's a gotcha with the default model binder that is not easy to know about but once you know it you no longer make the same mistake:
When you use a POST request, the default model binder uses your culture settings to parse the dates.
When you use a GET request, the default model binder uses CultureInfo.InvariantCulture to parse the dates and ignores your current culture settings.
Since you are using a GET request and passing the date as a query string parameter, you should format it using the invariant culture format when sending it in the url. The correct way to format your date as a query string parameter is yyyy-MM-dd.
You may take a look at the following blog post which gets into more details.
As someone who does a lot of work with US companies, I've had a lot of experience with date issues.
My best advice is to choose an unambiguous format when transmitting.
dd-MMM-yyyy
and
yyyy-MM-dd
Are safe bets, and will be successfully parsed by DateTime.Parse(obj).
If changing the date format is not an option, you should look at DateTime.ParseExact, which allows you to specify the exact format string you are after.
One approach would be to accept the date as a string and then manipulate it in the controller to the correct locale/culture.
Got the same problem using an #Html.Action(..) in a view. For this situation it can be solved by putting the DateTime in a model:
public class MyModel
{
public DateTime Value {get;set;}
}
and in the view:
#Html.Action("MyAction", new { myModel })
Note the new { } around the instance of MyModel, this way the DateTime is not converted to a string. This solution only works for Html.Action() and not for Html.ActionLink() or Url.Action() since MVC is doing a myModel.ToString() in the URL.
I have some DateTime fields on my MVC model classes - some which require a Date as input and others that require a Time as input - but both are DateTime properties.
Is it possible to have an EditorTemplate for DateTime that somehow produces a date picker to properties that are meant to be dates, and a time picker for properties that are meant to be times?
Yes, here is one way:
In ~/Views/Shared/EditorTemplates (or ~/Views/Shared/DisplayTemplates, create template files that use your favourite view engine (example uses Razor/C#)
file Date.cshtml
replace this with a real date picker
file Time.cshtml
replace this with a real time picker
Then, in your model:
[UIHint("Date")]
public DateTime DateProperty { get; set; }
[UIHint("Time")]
public DateTime TimeProperty { get; set; }
The UIHint attribute name has to match the file name of your template, and UIHint is in System.ComponentModel.DataAnnotations, so you will need the appropriate using statement/assembly reference if you don't have it already.
Alternatively, use a TimeSpan to represent your times - that is what DateTime returns for its TimeOfDay property...