0

I am trying to do date validation.

My requirement is user should not be able to select past date and time. It works fine until I change my local PC's date and time.

I am comparing user selected date and time with new Date() object of javascript but found that it fetches date from local machine's date. So if user changes his local machines date(set it to past date) then he would be able to select past dates.

Any server side(Java) solution is also acceptable. Try that too but Java's date object(java.util.date) also fetches date from local machine's date so no luck.

Thanks.

1
  • Where is your application is deployed? If you call new Date() then it will give the date of that machine (Server). So it should work. Commented Jul 25, 2016 at 9:19

1 Answer 1

1

For that you should get date and time from server.

serverDateTime.js

var xmlHttp;
function srvTime(){
    try {
        //FF, Opera, Safari, Chrome
        xmlHttp = new XMLHttpRequest();
    }
    catch (err1) {
        //IE
        try {
            xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
        }
        catch (err2) {
            try {
                xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
            }
            catch (eerr3) {
                //AJAX not supported, use CPU time.
                alert("AJAX not supported");
            }
        }
    }
    xmlHttp.open('HEAD',window.location.href.toString(),false);
    xmlHttp.setRequestHeader("Content-Type", "text/html");
    xmlHttp.send('');
    return xmlHttp.getResponseHeader("Date");
}
var st = srvTime();
var date = new Date(st);

Html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Server date/time</title>
<script language="javascript" src="serverDateTime.js"></script>
</head>
<script language="javascript">
var localTime = new Date();
document.write("Local machine time is: " + localTime + "<br>");
document.write("Server time is: " + date);
</script>
<body>
</body>
</html>

Hope it will work. Source : webdeveloper

Sign up to request clarification or add additional context in comments.

4 Comments

from which server it is getting date and time?
If you are running on your local machine then it will be your computer date and time.
No I have changed my local machine's date but your code returns the right date. Can you tell me how?
try changing date and then restart server. May be it will reflect changed date and time after that.

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.