4

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Pradeep Simha
  • 17,683
  • 18
  • 56
  • 107

7 Answers7

15

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);
Aaron Blenkush
  • 3,034
  • 2
  • 28
  • 54
Kal
  • 24,724
  • 7
  • 65
  • 65
  • So how do I achieve this? Like for eg: Server's time is: 9/25/2012 10:26 AM and I want it in milliseconds. And no I'm not asking for entire coding, but an Idea. – Pradeep Simha Sep 25 '12 at 14:27
  • 1
    System.currentTimeMillis() is the correct idea. Why do you think that returns the wrong time? – Kal Sep 25 '12 at 14:30
  • 2
    Because @pradeepsimha mentioned that he need the milliseconds value, probably he is returning the long returned from currentTimeMillis() and converting only on client side, and looses the timezone. – dan Sep 25 '12 at 14:35
  • 1
    @pradeep , System.currentTimeMillis() gives you the difference between current time and 1970 UTC. Since this information is known to you, you can create a Date object on hte client that represents UTC and then format it according to your client timezone. See this SO question for applying timezone offset - http://stackoverflow.com/questions/7670355/convert-date-time-for-given-timezone-java – Kal Sep 25 '12 at 14:44
7

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.

dogbane
  • 266,786
  • 75
  • 396
  • 414
4

tl;dr

Instant.now().getEpochMilli()

java.time

Other Answers use the terrible date-time classes (Calendar, Date) that are supplanted by the modern java.time classes built into Java 8 and later.

For a Jakarta EE web app, you are executing Java on the web server, not the web browser client. So running code to ask the current moment will give you the current moment on the server.

Capture the current moment as seen in UTC.

Instant instant = Instant.now() ;

Most of your work should be done in UTC. For presentation to the user, localize to a time zone of their choice.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ; 
ZonedDateTime zdt = instant.atZone( z ) ;

You said:

What I want is eg: Current server time is 9/25/2012:10:19AM in milliseconds.

To get a count of milliseconds since the epoch reference of first moment of 1970 in UTC (1970-01-01T00:00Z), interrogate the Instant. Beware of data loss, as the Instant may contain microseconds or nanoseconds in its fractional second.

long secondsSinceEpoch = Instant.now().getEpochMilli() ;

Table of date-time types in Java, both modern and legacy


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
2

If you like to return to the client the current time (System.currentTimeMillis()) from the server-side in milliseconds, you need to use the server's timezone when formatting/converting the value.

From Java 8 upwards we can use LocalTime localTime = LocalTime.now(); to get retrieve the current system time.

Also if you know the server timezone, you can use:

LocalTime localTime = LocalTime.now(ZoneId.of("GMT-06:00"));

Here "GMT-06:00" represents the server timezone expressed as an offset from GMT. You can use also the zone name like "Europe/London", etc. In Java™ Platform, Standard Edition 8 API Specification you can find more details.

But please note that using the timezone approach will only express the client time in the server timezone. If the client and server clocks are not properly synchronized, you will not get a time close to what is presented on the server. But if the times are properly synchronized, using a NTP client, and you do not need the exact time that the server is reporting (eg. only for presentation) this method is eliminating the server call.

dan
  • 13,132
  • 3
  • 38
  • 49
0

SERVER PROGRAM

import java.io.*;

import java.net.*;

import java.util.*;

class dateserver

{

public static void main(String args[])

{

ServerSocket ss;

Socket s;

PrintStream ps;

DataInputStream dis;

String inet;

try

{

ss=new ServerSocket(8020);

while(true)

{

s=ss.accept();

ps=new PrintStream(s.getOutputStream());


Date d=new Date();

ps.println(d);

ps.close();

}

}

catch(IOException e)

{

System.out.println("The exception is: "+e);

}   }   }

CLIENT PROGRAM

import java.io.*;

import java.net.*;

class dateclient

{

public static void main(String args[])

{

Socket soc;

DataInputStream dis;

String sdate;

PrintStream ps;

    try

    {

    InetAddress ia=InetAddress.getLocalHost();

    soc=new Socket(ia,8020);

    dis=new DataInputStream(soc.getInputStream());

    sdate=dis.readLine();

    System.out.println("The data in the server is: "+sdate);

    }

    catch(IOException e)

    {

    System.out.println("The exception is: "+e);

    }

}

}

Shivani Katukota
  • 859
  • 9
  • 16
gopi
  • 9
  • 1
0

Try this one:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM/dd/HH:mm");

    String cureentdate = sdf.format(new java.util.Date());
Zaid Mir
  • 29
  • 3
  • Hey Zaid. While this does work, try not to repeat a solution that already has been written next time. (Aaron already suggested that). Also you might want to edit to 'currentDate'. – corlaez Dec 05 '19 at 17:50
  • 1
    Hello corlaez i didn't check previous comments sorry it was already there. – Zaid Mir Dec 06 '19 at 05:34
0

If you want to get the timestamp from your server you could use

new Timestamp(new Date().getTime());

Nguyễn Đức Tâm
  • 1,017
  • 2
  • 10
  • 24