0

When i uploaded my razor pages application to server always getting this error 'The value '14/09/2022' is not valid for ...*.' i could figure out the issue,the format is interpreted as mm/dd/yyyy. i could not change the system dateformat for my server.

So what i did is i changed my applications Culture and UI-Culture Via IIS manager.

enter image description here

Even after that changes,its still showing the same issue.Im using Bootstrap datepicker. Any help would be appreciated.Thanks.

Edited

Startup.cs

public class CustomDateConverter : JsonConverter<DateTime>
        {
            public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                Debug.Assert(typeToConvert == typeof(DateTime));
                return DateTime.Parse(reader.GetString());
            }

            public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
            {
                writer.WriteStringValue(value.ToUniversalTime().ToString("dd'/'mm'/'yyyy"));
            }
        }

public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();

            services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddDebug()))
                    .UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });
            services.AddRazorPages().AddJsonOptions(options =>{
                options.JsonSerializerOptions.Converters.Add(new CustomDateConverter());
            });
            services.AddMemoryCache();
        }
Teena
  • 155
  • 1
  • 15

2 Answers2

0

You should post dates to the server in ISO 8601 format, which is yyyy-mm-dd. If you want to use a different format in the datepicker, you can use a hidden field to store a version of the date in yyyy-mm-dd format. You can use the onchange event of the date picker to populate the hidden field.

Or, if you can restrict the browser used to Chrome, Edge or Opera, you can just use an HTML5 input type="datetime-local" instead:

https://www.mikesdotnetting.com/article/352/working-with-dates-and-times-in-razor-pages-forms

Mike Brind
  • 28,238
  • 6
  • 56
  • 88
  • .My application works fine in my localhost where the system dateformat is dd/mm/yyyy. The system dateformat of my server where the application is deployed is mm/dd/yyyy,which i cannot change because of someother projects dependencies. – Teena Jan 05 '21 at 08:34
  • Yes - that's why you should work with ISO 8601 formats. Then you don't have to worry about regional settings on different servers. – Mike Brind Jan 05 '21 at 09:00
0

The ideal solution to set the date time format at server side is to setup the localization settings in startup:

services.Configure<RequestLocalizationSettings>(ops => 
{
    var cultures = new CultureInfo[] { new CultureInfo("en-GB") }
    ops.SupportedCultures = cultures;
    ops.SupportsUICultures = cultures;
    ops.DefaultRequestCulture = new RequestCulture("en-GB");
});

Then use localization middleware:

app.UseRequestLocalization();

Or you may set date format manually for a specific page:

var myCulture = new CultureInfo("en-GB");
myCulture.DateTimeFormat.ShortDatePattern = "dd/mm/yyyy";

CultureInfo.DefaultThreadCurrentCulture = myCulture;
CultureInfo.DefaultThreadCurrentUICulture = myCulture;

Or you may create a custom converter and configure it globally:

services.AddRazorPages()
    .AddJsonOptions(options =>
    {
        ops.JsonSerializerOptions.Converters.Add(new CustomDateConverter()));
    });

And of course don't forget to set the date format in bootstrap datetime picker as well:

$('.datepicker').datetimepicker({
    format: 'dd/mm/yyyy'
});
LazZiya
  • 5,286
  • 2
  • 24
  • 37
  • Hi @Laz Ziya, I tried to use the third option.But it showing like 'JsonOptions doesnot contain a definition for serializer settings'. i tried to use services.AddRazorPages() ,but still showing same error.Do i need to install anyother packages? – Teena Jan 05 '21 at 11:39
  • Hi @Teena, I've updated my answer (third option) to be compatible with razor pages and `System.Text.Json`, previously it was for `Mvc` and `NewtonsoftJson`. – LazZiya Jan 05 '21 at 12:39
  • hi @Laz Ziya , I changed accordingly still the date validation error is showing. I have updated my startup.cs file with DateTimeConverter function,and changed the rest of the code.But still its showing the same error for date. – Teena Jan 08 '21 at 07:39
  • I have edited my question.Could you please let me know if im doing anything wrong in that. – Teena Jan 08 '21 at 07:56
  • In your post, I did not find the DateTimeConverter function, how did you do it? – samwu Jan 08 '21 at 09:50
  • Hi @Teena, you will implement your own, the link already provided in the post. – LazZiya Jan 08 '21 at 12:26
  • @samwu Hi, In my post i renamed it as CustomDateConverter. And im facing the issue when im editing the records. When im adding i dont face any issues. – Teena Jan 10 '21 at 05:38
  • @Laz Ziya, i implemented my own functions by referring the codes in the link you provided. Still that error is showing. – Teena Jan 10 '21 at 05:40
  • @Teena Maybe you need to set the date format on the Control Panel, more information you can refer to this link: [https://code2night.com/Blog/MyBlog/How-to-set-Date-and-time-format-in-IIS-Manager](https://code2night.com/Blog/MyBlog/How-to-set-Date-and-time-format-in-IIS-Manager). – samwu Jan 12 '21 at 09:02