public JsonResult TimeValidation(string pickUp, string delivery)
{
var errorMessage = string.Empty;
var dateTime = DateTime.MinValue;
if (!DateTime.TryParse(pickUp, out dateTime))
errorMessage = "Invalid date";
if (!DateTime.TryParse(delivery, out dateTime))
errorMessage = "Invalid date";
}
4/29/2015 3:30:00 PM pickup from ie
4/30/2015 12:00:00 AM delivery from ie
4/29/2015, 3:30:00 PM pickup from firefox
4/30/2015, 12:00:00 AM delivery from firefox
its working good in chrome and firefox but its not converting to datetime in internet explorer 11 please obseve , between date and time
Assuming this is C# (looks like it is) and it is running on the server (not actually in the browser): You should check to see what the value of System.Globalization.CultureInfo.CurrentCulture is. See if it is different for a request coming from IE vs one of your other browsers. DateTime.TryParse(string, out DateTime) uses this value to help parse the string.
For instance, the date you provided: "28/04/2015 07:59:00" will cause TryParse to return false if the current culture is en-US, but if the current culture is es-MX, then it will return true.
I'm not sure why it would be different between browsers off the top of my head, but it's at least a place to start looking.
I came across a similar issue and the issue was the javaScript method
toLocaleDateString() in IE11 return string with some RTL characters! which results in invalid data and these characters aren't visible.
A simple fix using regex
toLocaleDateString().replace(/[^A-Za-z 0-9 \.,\?""!##\$%\^&\*\(\)-_=\+;:<>\/\\\|\}\{\[\]`~]*/g, '')
I tried the same regex at the back C# but it didn't work, however, I didn't want to spend more time on this so I just applied the front end solution.
More details, source
Related
I have temporarily set my browser language and locale to English - United Kingdom even though I am in the United States. I have removed "en-US" and now have "en-GB" as my only language preference.
In my Blazor WebAssembly site, on a component, I have a property that returns a string: myDate.ToString("d") + System.Globalization.CultureInfo.CurrentCulture.DisplayName; that renders on my page as 6/27/2020en (GB), where myDate is a DateTime set to June 27, 2020 at 00:00:00.000. My Blazor site has app.UseRequestLocalization(...) middleware set up.
Isn't is supposed to show the date in UK format, namely 27/06/2020? I can only guess that ShortDatePattern isn't getting properly set from CultureInfo.CurrentCulture. What could it be?
UPDATE: All WebAssembly component outputs show me that DateTimeFormatInfo.CurrentInfo.ShortDatePattern == "M/d/yyyy" even though CultureInfo.CurrentCulture.Name == "en-GB". Why might that be? What sets ShortDatePattern from the culture and can I "re-initialize" it?
An explicit call to myDate.ToString("d", System.Globalization.CultureInfo.GetCultureInfo("en-GB")); still strangely outputs the M/d/yyyy format (U.S. format). Why might that be?
UPDATE 2: I created a minimal example: File-New Project, Blazor Web Assembly, .NET 5 ASP.NET Core hosted. I replaced App.Razor with the following:
<div> current culture #(System.Globalization.CultureInfo.CurrentCulture.Name) </div>
<div> current date format #(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern) </div>
<div> today #DateTime.Now.ToString("d") </div>
That results in (unexpectedly):
Firefox browser settings (Edge and Chrome are similar and show the same issue):
That results in sending Accept-Language: en-GB,en-US;q=0.7,en;q=0.3--which seems to be the correct way to "prefer en-GB" and results in CultureInfo.CurrentCulture having the correct value.
I've tried it with Microsoft.AspNetCore.Components.WebAssembly.* nuget packages version 5.0.9, 5.0.11 - both show the same incorrect result.
UPDATE 3: The same minimal project in 6.0.0-rc.1 works and gives the right date format! Is this really a Blazor 5 bug that they never fixed?
For .NET 6+, this seems to be fixed.
For .NET 5, I could not find the root cause, so I needed to code this workaround, which needs to be called explicitly when needed. Obviously this is undesirable if we can find a better solution to allow the use of DateTime.ToString as intended.
/// <summary>
/// Returns a short date-only string from a date/time value, based on the user's current culture.
/// </summary>
public static string ToLocalShortDate(this DateTime value)
{
// this is needed because I can't get localization to work -- see https://stackoverflow.com/q/69542125/7453
// (if we can fix, better to use DateTime.ToString("d"))
string format;
// countries taken from https://en.wikipedia.org/wiki/Date_format_by_country
if (CurrentCulture.Name.EndsWithAny("US", "CA", "ZA", "KE", "GH", "en"))
format = "MM/dd/yyyy";
else if (CurrentCulture.Name.EndsWithAny("CN", "JP", "KR", "KP", "TW", "HU", "MN", "LT", "BT"))
format = "yyyy-MM-dd";
else format = "dd/MM/yyyy";
return value.ToString(format);
}
/// <summary>
/// Returns true if and only if a string ends with any of some strings.
/// The value will not match a null reference.
/// </summary>
public static bool EndsWithAny(this string value, params string[] allowedValues) =>
allowedValues != null && value != null && allowedValues.Any(s => CurrentCulture.Name.EndsWith(s));
I am using kendo datePickerFor
Code into model=====
[DataType(DataType.Date)]
[Display(Name = "Date:")]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}",
ApplyFormatInEditMode = true)]
public DateTime TransactionDate { set; get; }
Into view page====
#(Html.Kendo().DatePickerFor(m => m.TransactionDate)
.Format("MM-dd-yyyy")
.ParseFormats(new List<string>()
{
"MM-dd-yyyy"
})
)
Also use javascript====
$(function () {
kendo.culture("en-US");
})
My kendo DatePickerFor is inside a form.
when I submitting the form giving error - "The value '09-16-2016' is not valid for Date:."
My local machine date format is "dd-MM-yyyy".
When I set this format into datepicker,form submitted correctly.
But I want to set specific format which does no depend on local machine format
Please know me how to solved this problem.
Normally, you would want to match the cultures on the client and on the server:
http://docs.telerik.com/kendo-ui/aspnet-mvc/globalization#match-cultures
The server-side culture can be set, depending on the regional information provided in the browser's request.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language
If there is a valid reason not to do this, then you will have to manually take care of submitting the date value in the correct format, expected by the server.
I had similar problem - the best description I found (but not a solution) is here: https://blog.gerardbeckerleg.com/posts/kendo-ui-mvc-grid-datepicker-in-line-and-in-cell-edit-validation-error-the-value-is-not-valid/
My local machine culture date format is dd.MM.yyyy, in my multilanguage app I wanted to force always one date format: yyyy-MM-dd, so I added (to never show local date format)
#(Html.Kendo().DatePickerFor(m => m.TransactionDate)
.Format("yyyy-MM-dd"))
Problem occurred while saving changes only inside kendo grid when I used In-Line edition and only for my local machine culture, which does not allow format with month-first. When I input date in format yyyy-MM-dd, after accepting this change it somehow swapped month and day, and my date 2020-01-05- (january 5th) was saved as 2020-05-01 (may 1st). And when a day was > 12 same error as yours occured (e.g. for date 2020-12-31 - december 31st it couldn't change 31 info a month, and I got error: "The value 31.12.2020 is not valid for Date"
In error messsage a given format was exactly like my local machine culture (dd.MM.yyyy -> 31.12.2020) but error occured so the date was treated as MM.dd.yyyy and in this format 31.12.2020 is not valid indeed.
What was strange I noticed different behaviour when I ran same application from client machine (but same local culture as mine) and when I was debugging in VS on local machine (on a local machine I couldn't reproduce an error, only on client machine)
What I did?
I checked if I load proper kendo culture (I did): kendo.culture("pl-PL");
I changed kendo.culture.pl-PL.min.js date format info yyyy-MM-dd. To not change min.js file I did as an extension js method (notice the first true parameter!):
var customCulture = $.extend(true, kendo.culture(), {
calendars: {
standard: {
patterns: {
d: "yyyy-MM-dd",
g: "yyyy-MM-dd HH:mm",
G: "yyyy-MM-dd HH:mm:ss"
}
}
}
}
);
It forces takes given date formats and pushes (merges) them into currently loaded kendo.culture(), what does the trick. Because I always want to show yyyy-MM-dd format I is what I need.
The idea of solution was taken from here: https://www.telerik.com/forums/calendar-customization-764d6343160b
I have an asp.net application that allows users to create subscriptions for SSRS reports.
All my reports have #StartDate and #EndDate parameters which have default values of
=Today.AddDays(-14)
and
=Today
respectively.
My c# code takes checks the defaultvalue of the parameters when loading the subscription form, to pre-populate AspxDateEdit controls. This all works fine on my dev environment (NZ).
ItemParameter[] Parameters = _Rs.GetItemParameters(_ThisReportPath, null, true, null, null);
if (Parameters.Any())
{
foreach (ItemParameter Rp in Parameters)
{
if (Rp.ParameterTypeName == "DateTime" && Rp.PromptUser)
{
var MyDtControl = new ASPxDateEdit
{
ID = "dtParam" + MyTable.Rows.Count
};
DateTime MyFormattedDisplayDate = Convert.ToDateTime(Rp.DefaultValues[0], CultureInfo.CurrentCulture.DateTimeFormat);
MyDtControl.Date = MyFormattedDisplayDate.Date;
}
}
}
The initial website will be residing on a server in Australia, with subsequent rollouts to various countries around the world, so I need to keep the format of DateTimes dynamic (Culture specific).
When loading the subscription form for a report on the live system I get the error “String was not recognized as a valid DateTime.” Dumping the values of the Parameter.DefaultValues[0] shows that the default value on the AU server is in US form (MM/dd/yyyy) which is causing the errors. Logging code:
SQLReportsLogic.Log(MyLog, "(Line 599 - LoadParams)Default Param Value:" + Rp.DefaultValues[0] + "/ ServerDateFormatToday:" + DateTime.Now);
Resulting output:
(Line 599 - LoadParams)Default Param Value:3/24/2015 12:00:00 AM/ ServerDateFormatToday:24/03/2015 7:14:47 AM
The format is expected to align with the culture info of the server which would be dd/MM/yyyy.
- The report language is set to User!Language
- The Server System Locale is English(Australia)
- The Server Location is Australia
- The Server Datetime format is set to ShortDate=d/MM/yyyy LongDate=dddd, d MMMM yyyy
- The Server Language is set to English (Australia)
- The Reporting Services Service is running under Local System Account
- WWW is running under Local System Account
- SSRS is running in Native Mode
Where specifically does SSRS get the DateTime Format from when determining the format for =Today()? As I understand my research to date, this should be generating =Today() in the system assigned format of dd/MM/yyyy
I have also tried formatting the DefaultValue of the parameters to
- “yyyy/MM/dd hh:mm:ss” = The DefaultValue expression for the report parameter ‘StartDate’ contains an error: Input string was not in a correct format
- “yyyy/MM/dd hh:mm” = The DefaultValue expression for the report parameter ‘StartDate’ contains an error: Input string was not in a correct format
- “yyyy/MM/dd” = The DefaultValue expression for the report parameter ‘StartDate’ contains an error: Input string was not in a correct format
- DateFormat.ShortDate = The property ‘DefaultValue’ of report parameter ‘StartDate’ doesn’t have the expected type.
- DateFormat.LongDate = The property ‘DefaultValue’ of report parameter ‘StartDate’ doesn’t have the expected type.
- DateFormat.GeneralDate = The property ‘DefaultValue’ of report parameter ‘StartDate’ doesn’t have the expected type.
It would seem that unless I can resolve the way SSRS renders =Today() that my hands are tied. As I understand it I need to find the issue with the SSRS installation using the incorrect Culture? Is it looking it up in the registry somewhere?
I am using VS2012 (11.0.61030.00 Update 4) with SSDTBI Plugin (MSSQL Server Reporting Services Designers Version 11.0.3436.0)
Finally found the right search terms to use and found a solution after two days - to override the SSRS GetWebRequest as described here..
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/f147c641-d5c2-49e8-97f6-b654bec8366d/datetime-format-for-webservice-api-calls?forum=sqlreportingservices#0c223835-dd5c-4471-b736-1d9dad014144
public partial class ReportingService : DevReportService.ReportingService2010
{
/// <summary>
/// Gets or sets the culture that is used when generating the report.
/// </summary>
/// <value>The culture that is used when generating the report.</value>
public CultureInfo Culture { get; set; }
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest request = base.GetWebRequest(uri);
CultureInfo culture = this.Culture ?? CultureInfo.CurrentCulture;
request.Headers.Add(HttpRequestHeader.AcceptLanguage, culture.Name);
return request;
}
}
I have a C# Web Service running on a Windows machine, and i have this code:
Details = tInfoRequestHistory.Select(i => new AppJsonDetails
{
Type = i.PlatformUserId == null ? "Request" : "Response",
Date = i.Date.ToString("D"),
Time = i.Date.ToString("hh:mm tt"),
Text = i.Comment,
}).ToArray()
And i'm receiving this JSON in my app:
{
Date = "lunes, 12 de enero de 2015";
Text = "402\\nGarcia\\n01/12/15 12:52 \\nBla bla";
Time = "11:52 ";
Type = Request;
}
As you can see i'm missing the PM/AM (in fact there is a blank space) in the node "Time" that is generated with this instruction i.Date.ToString("hh:mm tt")
If i execute my code in my development machine everything is working ok.
I'm using windows server 2012 and the last IIS 8.0 and i have just change the regional settings of my server to match my development machine so i'm reading in my server clock "12:00 PM"
I'm sure that this is some configuration i'm missing in the Server or in the IIS or maybe in the Web.config.
Any help or idea will be really appreciated.
Well, since you using DateTime.ToString() without any IFormatProvider, sounds like your CurrentCulture's AMDesignator or / and PMDesignator properties are empty string.
I would suggest a use InvariantCulture as a IFormatProvider like;
i.Date.ToString("hh:mm tt", CultureInfo.InvariantCulture);
Or change current culture that have non-empty AMDesignator and PMDesignator properties in your windows machine region settings.
I have two laptops both with windows xp sp3, vs 2010 and target framework .Net 3.5. When processing DateTime variable, I found that with laptop1
DateTime oldOrderDate;
string strnewdate = string.Empty;
CultureInfo provider = CultureInfo.InvariantCulture;
if (DateTime.TryParse(items[1], out oldOrderDate))
strnewdate = oldOrderDate.ToString("yyyy-MM-dd");
returned an exception "string was not recognized as a valid datetime" , but the codes below:
oldOrderDate = DateTime.ParseExact(items[1], "dd/MM/yyyy", provider);
strnewdate = oldOrderDate.ToString("yyyy-MM-dd");
works. OTOH, with laptop2,
oldOrderDate = DateTime.ParseExact(items[1], "dd/MM/yyyy", provider);
strnewdate = oldOrderDate.ToString("yyyy-MM-dd");
returned an exception "string was not recognized as a valid datetime" , but the code below:
if (DateTime.TryParse(items[1], out oldOrderDate))
strnewdate = oldOrderDate.ToString("yyyy-MM-dd");
works. So, my question is how I should do processing of a DateTime variable to work in both laptops. I'd really appreciate any advice you could give me. Thank's in advance.
I am not sure but look at the regional settings of date and time in control panel. In my systems they also differ and hence different results.