简体   繁体   中英

Java : What are the way to sync time between client and server

My web server is in Us i am posting comment in India. I am storing comment time as server time. Instead of showing just now it shows 6hr before means there is difference of 6 hour between actual comment time and server time.

I am using Spring-MVC on server side and cassandra as DB Here is how i am taking time of a comment:

long commentTime = new Date().getTime()

here how i am displaying date

SimpleDateFormat sdf  = new SimpleDateFormat("YYYY MM dd hh:mm:ss a");
lk=Long.parseLong("date in long as string");
myPageList.setCreatedOn(sdf.format(new Date(lk)));

What are the way to sync time between client and server ?

Start using a time API which supports time zone conversions (eg Java 8's java.time or Joda-Time ). Don't persist a local date in the data base. Store the point of time in the database (ie with a time zone).

On the presentation side you will have to know the client's local time zone. One method is storing that information in a user profile (if you have authenticated users). Another method might involve some Javascript magic. With the local time zone and a proper time API you can easily present the stored point of time in the local 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