Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
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());
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
}
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
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
// 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);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
I have the following method that has been for a very long time in a legacy codebase.
public static Calendar nowAsCalendar(String timeZone){
Calendar FDRCal = GregorianCalendar.getInstance(timeZone);
FDRCal.setTime(now());
Calendar cal = Calendar.getInstance();
cal.set(1, FDRCal.get(1));
cal.set(2, FDRCal.get(2));
cal.set(5, FDRCal.get(5));
cal.set(11, FDRCal.get(11));
cal.set(12, FDRCal.get(12));
cal.set(13, FDRCal.get(13));
cal.set(14, FDRCal.get(14));
}
We are setting a brand new Calendar instance cal that uses the default timezone so I think it should break as we are not setting the timezone in the new Calendar instance. Am I overlooking something?. What is the best way to set the current date with a timezone?
In Calendar.getInstance() the new instance uses your system's default time zone, so failing to set it the time zone won't cause anything to break, unless you require the time zone to be something other than the default.
However, Calendar is an obsolete class with many flaws, and it's really best not to use it any more. The more modern class to represent a date and time with a timezone is java.time.ZonedDateTime.
You can instantiate one of these, using the default time zone and the current date and time, by writing ZonedDateTime.now(). There's also a version where you can pass in a ZoneId for a time zone, if you want a different time zone from the default - that is, you can write something like
ZoneId sydneyTime = ZoneId.of("Australia/Sydney");
ZonedDateTime rightNow = ZonedDateTime.now(sydneyTime);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
This post was edited and submitted for review 11 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Code
Date dates = new Date(Long.MAX_VALUE);
output -
292278994-08-17 12:42:55
I want to get the largest date today onwards. How to get this using another way.292278994 this year cant save my DB I need only 4 characters for the year.
To get the boundary dates of the current year, you can use the java.time API and set the month/day values to january 1st and december 31st respectively:
LocalDateTime now = LocalDateTime.now();
LocalDateTime startOfYear = now.withMonth(1).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
LocalDateTime endOfYear = now.withMonth(12).withDayOfMonth(31).withHour(23).withMinute(59).withSecond(59).withNano(999999999);
System.out.println(startOfYear);
System.out.println(endOfYear);
Output:
2022-01-01T00:00
2022-12-31T23:59:59.999999999
Epoch milliseconds are milliseconds counted from the very first moment of 1970 and they are stored as long in Java. That means Long.MAX_VALUE will get you the moment in time that is as far in the future as this representation allows. A moment that is beyond some maximum date of the current year, like some hundred million years beyond…
If you are on Java 8 or higher and try to use an Instant with Long.MAX_VALUE like this:
public static void main(String[] args) {
// use the greates Long as epoch millis and create an Instant from it
Instant instant = Instant.ofEpochMilli(Long.MAX_VALUE);
// represent the Instant as date and time of day in a specific zone
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.of("UTC"));
// define the output format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
// and print the
System.out.println(zdt.format(dtf));
}
You will get the following output:
+292278994-08-17 07:12:55
You may want to adjust the ZoneId to the desired one and remove the leading plus from the output…
But basically understand that epoch milliseconds are not years.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed last month.
Improve this question
I'm building a simple organizer app and trying to pick a class to keep my date and time in object. Which classes should I use? I've seen that lots of methods in Date class are deprecated. Maybe Calendar then? Recommend something. Thanks.
It will depend on what kind of date / time you want.
System.currentTimeMillis() - this will give you a simple numeric value expressed as the number of miliseconds after the UNIX epoch as a long.
If you want year, month day format you could use one of these:
new Date() - this will give you a Date object initialized with current date / time. This is deprecated as the API methods are mostly flawed.
new org.joda.time.DateTime() - this will give you a joda-time object
initialized with the current date / time. Joda-time includes a great API for doing anything involving time point an duration calculations. With Java 8, however, this is no longer true
Calendar.getInstance() - this gives you a Calendar object initialized witht he current date / time, using the default locale and TimeZone.
If you just need a simple way to output a time stamp in format YYYY.MM.DD-HH.MM.SS - a very frequent case - then use this:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
Instant - if you want to do any work with business logic and data storage/exchange it should be done in UTC, as a best practice. To get the current moment in nanoseconds use the Instant class:
Instant instant = Instant.now();
You can also adjust that Instant into other time zones. Apply a ZoneId object to get a ZonedDateTime.
ZoneId zid = ZoneId.of("Europe/Paris"); //create zone id
ZonedDateTime zdt = instant.atZone(zid); //pass zone id get the adjusted zoned date time.
LocalDate - this class represents a date-only value without time-of-day and without time zone.
ZoneId zid = ZoneId.of("Europe/Paris");
LocalDate today = LocalDate.now(zid); //Always pass in a time zone
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am reading time from the DB in format MM/dd/yyyy hh:mm a z now I want to display this time in user local timezone. So my question are:
Where should it be done client side or server side?
Is there build in lib for this purpose?
UPDATE
So I decide to do conversion in server, therefore I have method definition as following with parameter date from server and time zone offset of the client time.
public String convertToLocalDateTime(Date dateFromDB, Integer offSetMins) {
//1. dbDateInUTC = Convert dateFromDB to UTC
//2. return offSetMins + dbDateInUTC;
}
I am not sure how I can do step (1). Any suggestion?
To ensure user gets it's timezone you can do it at client side, for this you can use a library like Moment.js or date.js.
Just get the date of the server, transform it in long:
Date d = // date from server
long milliseconds = d.getTime();
Send to client and get the offset:
The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, if your time zone is UTC+10 (Australian Eastern Standard Time), -600 will be returned. Daylight saving time prevents this value from being a constant even for a given locale.
var offset = new Date().getTimezoneOffset();
Then you just have to get the corrected date 1 minute = 60.000 milliseconds :
var dateInMilliseconds = dateFromServer - (offset * 60000);
Also, if as #jon suggested you want to do it telling server client's timezone, get the offset and send it to java to transform the date:
long offsetMillis = offset * 60000;
Date d = new Date(offsetMillis);
In my practice, to avoid complecity and confusion, it is better to:
For operating and persisting dates within the application use UTC timezone.
Display date/time to the end user, using the local timezone.
Thus, server side all dates/times in UTC and client-side in local TZ.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to build a program that libraries can use. The user inputs the date they loaned the book, and it calculates that date + 5 days (when the book is due). Then checks if the current date is before or after the due date. Then says if it is late or not.
Use SimpleDateFormat to take the user input (as a String), and
convert it to a Date. Use Calendar for adding days to a given Date.
See also:
SimpleDateFormat
Date
Calendar
Use JodaTime instead and then you can call plusDays() on a DateTime object. There is also an isBefore() method as well. Here is a simple example:
DateTime loanDate = new DateTime();
DateTime dueDate = new DateTime().plusDays(8);
DateTime date = loanDate.plusDays(5);
System.out.println(date.isBefore(dueDate));
This returns true as the date is before the due date.