Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current server time in Java?

Tags:

java

time

How can I get current server's time in Java? I tried System.currentTimeMills() but it is returning me the client's time not server time. I want to get "Server's" time in milliseconds.

I searched in net, but I dind't get. All the code returns value from 1970. What I want is eg: Current server time is 9/25/2012:10:19AM in milliseconds.

like image 426
Pradeep Simha Avatar asked Nov 29 '22 02:11

Pradeep Simha


2 Answers

System.currentTimeMillis() returns number of milliseconds since 1970.

If you run it on the server, you will get the server time. If you run it on the client (e.g. Applet, standalone desktop app, etc.) you will get the client time. To get the server date on the client, set up a call that returns the server time in the formatted string to the client.

If you want the date formatted a certain way , first create a Date() object and then format it using SimpleDateFormat

Date d1 = new Date();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/YYYY HH:mm a");
String formattedDate = df.format(d1);
like image 108
Kal Avatar answered Dec 05 '22 23:12

Kal


If you want your client to get the server's time, you will have to make a request to the server and have the server send back its current time in the response.

like image 45
dogbane Avatar answered Dec 05 '22 21:12

dogbane