How can I make same format of date between server and client. My server's date format is yyyy/mm/dd. But the client's date format is dd/mm/yyyy. When the model post to server, the system cannot bind date from client form data because of client's date format. Please see sample code below.
In Controller
Function TestDateFormat() As ActionResult
Dim testDateFormatVM As New TestDateFormatVM
testDateFormatVM.FormatDate = New Date(1989, 8, 22)
Return View(testDateFormatVM)
End Function
In Model
Public Class TestDateFormatVM
Public Property FormatDate As DateTime
End Class
In View
#ModelType ListTest.TestDateFormatVM
#Code
ViewData("Title") = "TestDateFormat"
End Code
<h2>TestDateFormat</h2>
#Using Html.BeginForm("Display", "Home")
#Html.TextBoxFor(Function(item) item.FormatDate)
#Html.HiddenFor(Function(item) item.FormatDate)
#<input type="submit" value="SUBMIT" />
End Using
Before form submission, the date of hidden field was updated form javascript with "dd/mm/yyyy" dateformat. When the form posts to server, the model gets error due to wrong datetime format because the server format is mm/dd/yyyy.
I would like to know what is the best way to make same date format between server and client until server culture is changed.
Thanks all
Related
I am currently developing asp.net core(Framework 3.1) application. I am getting date from database and storing it in string(tried using DateTime but didn't work). Here's my code in model:
public string TranDate { get; set; }
salesList.Add(new SalesData()
{
TranDate = dt.Rows[i]["TRANDATE"].ToString(),
});
It displays date in "2020/06/06 00:00:00" format.
In partial view:
<td>
#Html.DisplayFor(modelItem => item.TranDate)
</td>
Now I want to display date in "dd/MM/yyyy" format like "06/06/2020" in my partial view. I have tried many ways like display templates, editor templates, String.Format but nothing works. Please help!
Please try something like the following;
string formattedDate = DateTime.Now.ToShortDateString(); //set a default date
if (DateTime.TryParse(TranDate, out DateTime usersDate))
{
formattedDate = usersDate.ToShortDateString();
}
TranDate = formattedDate;
Some of this may be too much, but the core premise is that using the DateTime.TryParse method ensures that the date being passed into it (your "TranDate" parameter) can even be converted to a date. I know it is coming from the database and likely a Date field itself, but we really should not trust that, to be sure.
[HttpPost]
public JsonResult GetSearchedResults(string searchedHotel)
{
var searchingHotels = clsRepository.GetSearchedResults(searchedHotel, );
return json etc etc
}
This is my Controller. Just Like String, I need to pass Date Datatype. I have A field Name in DataBase of Type Date.Now I need to pass this.how to pass a datatype DATE.?
I have a DatePicker is my main page. When i choose A date from Datepicker, that will be saved in a variable in my Jquery file. so I need to pass this variable to controller.i need to check whether selected date and date in DataBase are equal.
Just change the datatype of your action parameter to DateTime. The default modelbinder will try to convert the value of the sent request parameter to a DateTime value.
public JsonResult GetSearchedResults(DateTime myDateParameter)
{
// do whatever you want with your date
}
Make an ajax POST request to your action with the date as a parameter.
Use jQuery to make the request. See the dosc on how you can do it: http://api.jquery.com/jQuery.ajax/
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.
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.