2

I have a Custom Attribute for DateTime validation with given dateformat and also javascript validator which are provide me both client side and server side validation. But now I should change my datetime validation so that it would be performed according clients local DateTime format and I do not know how.

I couldn't find anything that help me.

So please advise me how can I implement at least client side DateTime validation or how can I get client's date format by javascript.

1 Answer 1

1

If you can determine the locale of your user, you can use .Net globalization classes to assist with server-side parsing of date time strings. For example:

// Parsed as January 4th
var dt1 = DateTime.Parse("1/4/2013", new CultureInfo("en-US"));

// Parsed as April 1st
var dt2 = DateTime.Parse("1/4/2013", new CultureInfo("en-GB"));

But the best thing to do is avoid this entirely. In your JavaScript code, get the value back as an ISO8601 string - which is culture invariant. Native browser support for this varies. The built-in functions work in IE9+.

// This returns an ISO formatted date, in UTC.
var s = yourDate.ToISOString();

One way to get full browser support, and get an ISO date without converting to UTC, is to use the moment.js library, where ISO8601 is the default format:

// This returns an ISO formatted date, with the user's local offset.
var s = moment(yourDate).format();

// This returns an ISO formatted date, in UTC.
var s = moment(yourDate).utc().format();

When you send these values to the server, you can parse them in your .Net code without concern for culture. The format is already culture invariant. To prevent the server's time zone from interfering, you should parse them as a DateTimeOffset:

// assuming this is an ISO value you got from the client:
var s = "2013-04-20T09:00:00-07:00";

// simply parse it
var dto = DateTimeOffset.Parse(s);

// if you don't care about the offset at this point:
var dt = dto.DateTime;

Of course, if you want to fail gracefully, you can do this instead:

DateTimeOffset dto;
var isValid = DateTimeOffset.TryParse(s, out dto);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for your answer, but actually my problem is to validate user's Date input so that it was correctly formatted by their culture's DateTime format otherwise do not allow to post it.
@Gohar - You need to know their culture setting, and then you can use DateTime.TryParse. There are a few other questions on SO about detecting the user's culture info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.