1

How to get today's date and time NOT DEVICE i.e actual

I have tried this and many but all they give device time

String date = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss", Locale.getDefault()).format(new Date());

4 Answers4

1

You can get time details from internet and then use it. Just Internet is required.

Use android.net.sntp.SntpClient class.

SntpClient client = new SntpClient();
int timeout = 50000;
if (client.requestTime("time-a.nist.gov", timeout)) {
    long time = client.getNtpTime();
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(time);
    calendar.getTime();  // this should be your date
}
Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
0

1) Your code will not compile due to applying a Format with hours and minutes to a Date
2) You are using default Locale of the device so it will return the local date time.
3) You need to use a timezoned time and apply the timezone of Greenwitch to get current DateTime without any timezone applied.
Check ZonedDateTime for more informations

IQbrod
  • 2,060
  • 1
  • 6
  • 28
0

If I understood you correctly, you might want to get the timestamp from a NTP (Network Time Protocol) server. And java has already had libraries to support your need. Check this out. (StackOverFlow) How to make my java app get global time from some online clock

Minh Dao
  • 827
  • 8
  • 21
0

// get current default time System.out.println( Calendar.getInstance().getTime());

// get different time zone
ZoneId zoneId = ZoneId.of("America/Los_Angeles");
LocalTime localTime=LocalTime.now(zoneId);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
String formattedTime=localTime.format(formatter);
System.out.println("Current time of the day in Los Angeles: " + formattedTime);
ankur
  • 1
  • 1