简体   繁体   中英

How to get current date, month, and year in Javascript instead of user PC's date, month and year?

How can I get the current date, month and year in Javascript. I am using getFullYear() and getMonth() functions of JS's Date object. But these functions return the year and month of my PC. If I change my PC's date to an older or upcoming date, then these functions return those month and year.

How I can get current date, month and year, no matter what date user PC's shows?

Short of your code going out to a trusted source such as a known NTP server, you're going to be at the mercy of the local machine.

Even if you did attempt to go out to a trusted source, the local machine could subvert it by capturing your TCP traffic.

And, even if you created your own trusted machine which used encryption to deliver the correct date and time, a local machine could subvert that, simply by changing the JavaScript.

Bottom line, it's an arms race, and almost certainly a fools errand to think you can secure your code against everything. Perhaps it may be a good time to actually think why you need an accurate date in the first place.

If we knew that, we may be able to give advice outside the box you're currently in. Far too many questions of the form "How do I do X in a Y way?" discount a huge number of non-Y potential solutions :-)

JavaScript does not work by magic. The only indication of the date it has is the date the machine it's being run on has.

Well i think you can do something like this

var ds = ... // Some ajax call to server 
var d = new Date(ds);

And after you have date you can easily get month and year part from date

简而言之,如果您只需要月份和年份,您可以在服务器级别构造 datetime 对象并将其作为字符串并从该变量中放入 javascript 您可以再次重建 javascript 日期对象,您可以从中提取 getyear 和 getmonth 任何您需要的东西。

You did not mention your server side language but I solved it this way in Grails :

<script>
var serverDate=new Date(${new Date().getTime()});
//use serverDate
</script>

As you can see ${new Date().getTime()} is Grails code being executed at server side, so its value will be something like 1420700836298 (datetime) then var serverDate=new Date(1420700836298); will executed at client side;obviously serverDate will be date object according to the server time.

So your task will be to replace ${new Date().getTime()} with your server side lang.

NB This is not ajax call, it will execute only once ; when the page loads for the first time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM