Get local Date as long in android, confusion maybe? - java

I might have little confusion about Date in android/java. What I know is when calling new Date() it creates a Date instance with current UTC date and time, Right ? Because Date in java don't have any time zone thing, So if I call
new Date().getTime() I will get a long value(time stamp) as UTC, not as local time, right ?
And to show date, we use 'DateFormat' and it has time zone info. So when I call DateFormat.getDateTimeInstance().format(new Date()) I will get a string with local time.
But how do I get long value(time stamp) of local time ?? I found this answer but is that the only way ? or something more simple ?
Thank you :)

So if I call new Date().getTime() I will get a long value(time stamp) as UTC, not as local time, right?
Well, it will give you the number of milliseconds since Jan 1st 1970 00:00:00 UTC, yes. It's not "in" UTC particularly; it's just a number of milliseconds since an arbitrary epoch.
But how do I get long value(time stamp) of local time?
You don't, basically. That turns out not to be a particularly useful concept. If you think about it, a timestamp is just an instant in time - it's independent of time zones. You can express the Unix epoch in any time zone; it just happens to normally be expressed in terms of UTC.
If you need the local date/time for a particular timestamp, you just need to remember the timestamp itself and the relevant time zone. If you give us more information about what you're trying to achieve, we may be able to help more.

See Date.getTime javadocs: Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. There is no local timestamp. There can be only different textual date / time representations of it.

You can try these to get local date.
String s=new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH).format(new Date());
or
Calendar c=Calendar.getInstance(TimeZone.getTimeZone("GMT"));

But how do I get long value(time stamp) of local time ??
A local date-time in a timezone is just a representation of the universal instant in that timezone. The new java.util.Date() gives us that universal instant i.e. it simply represents an instant on the timeline — a wrapper around the number of milliseconds since the UNIX epoch (January 1, 1970, 00:00:00 GMT). Since it does not hold any timezone information, its toString function applies the JVM's timezone to return a String in the format, EEE MMM dd HH:mm:ss zzz yyyy, derived from this milliseconds value. In other words, the same milliseconds will be represented as different date-times in different timezones. The vice versa: at any given moment, date-times in different timezones will give us the same number of epoch milliseconds.
java.time
The object corresponding to new java.util.Date() in java.time, the modern Date-Time API is Instant.now().
A demo of java.time, the modern Date-Time API:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// Let's assume 2021-06-26T23:35:50 is the local date-time in India
LocalDateTime ldtIndia = LocalDateTime.parse("2021-06-26T23:35:50");
Instant instant = ldtIndia.atZone(ZoneId.of("Asia/Kolkata")).toInstant();
long millis = instant.toEpochMilli();
System.out.println(millis);
}
}
Output:
1624730750000
ONLINE DEMO
You can convert Instant and java.util.Date to each other using
java.util.Date#from(Instant) and java.util.Date#toInstant().
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Related

How to parse offset it is not specified?

I have time 12:00:00 in format HH:mm:ss.
I know that this time comes from server witch is setup with +3 offset.
If i use SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");, it parses time with regard to device, which can be in a different timezone.
Is there another way to parse it with regard to +3 offset except adding it to the original string?
First, should your server rather send the time in UTC? If clients are everywhere, this would seem more time zone neutral and standardized. However, the way to handle it in code wouldn’t be much different. In any case the server offset form UTC could be constant:
private static final ZoneOffset serverOffset = ZoneOffset.ofHours(3);
In real code you will probably want to make it configurable somehow, though. To parse:
OffsetTime serverTime = LocalTime.parse("12:00:00").atOffset(serverOffset);
System.out.println(serverTime);
This prints
12:00+03:00
Since your time format agrees with LocalTime’s default (ISO 8601), we need no explicit formatter. If a representation of the time with offset is all you need, we’re done. If you need to convert to the user’s local time, to do that reliably you need to decide both a time zone and a date:
LocalTime clientTime = serverTime.atDate(LocalDate.of(2018, Month.JANUARY, 25))
.atZoneSameInstant(ZoneId.of("Indian/Maldives"))
.toLocalTime();
System.out.println(clientTime);
With the chosen day and zone we get
14:00
Please substitute your desired time zone and date.
Just hypothetically, if you knew the user’s offset from UTC, you could use just that:
LocalTime clientTime = serverTime.withOffsetSameInstant(ZoneOffset.of("-08:45"))
.toLocalTime();
The example yields 00:15. However, no one knows when the politicians introduce summer time (DST) or other anomalies in the user’s time zone, so I discourage relying on an offset alone.
And yes, I too am using java.time. SimpleDateFormat is not only long outdated, it is also notoriously troublesome, so java.time is what I warmly recommend.
Set the timezone on your SimpleDateFormat object:
SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss");
fmt.setTimeZone(TimeZone.getTimeZone("GMT+03:00"));
I recommend you use the Java 8 date and time API (package java.time) instead of the old API, of which SimpleDateFormat is a part.
Using the Java 8 DateTime API:
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("HH:mm:ss");
LocalTime clientLocalTime = LocalTime
.parse("12:00:00", formatter)
// Create an OffsetTime object set to the server's +3 offset zone
.atOffset(ZoneOffset.ofHours(3))
// Convert the time from the server timezone to the client's local timezone.
// This expects the time value to be from the same day,
// otherwise the local timezone offset may be incorrect.
.withOffsetSameInstant(ZoneId.systemDefault().getRules().getOffset(Instant.now()))
// Drop the timezone info - not necessary
.toLocalTime();

Jboss Java Date daylight saving time

Have an issue where, when clocks are moved due to a Daylight savings time (twice a year), dates are not correct in Java (I am based in Central Europe: GMT+2 in summer, GMT+1 in winter)
If time is moved 1 hour ahead, new Date() still returns old time (1 hour behind of current time).
In Java 7, can this be solved, without restarting the Jboss application servers?
If I change the time manually in Windows, reproduce the problem: Date is not updated to the system date unless jboss is restarted.
Calendar c = Calendar.getInstance();
c.setTime(new Date());
In Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes.
With this, you can handle DST changes easily.
First, you can use the org.threeten.bp.DateTimeUtils to convert from and to Calendar.
The following code converts the Calendar to org.threeten.bp.Instant, which is a class that represents an "UTC instant" (a timestamp independent of timezone: right now, at this moment, everybody in the world are in the same instant, although their local date and time might be different, depending on where they are).
Then, the Instant is converted to a org.threeten.bp.ZonedDateTime (which means: at this instant, what is the date and time at this timezone?). I also used the org.threeten.bp.ZoneId to get the timezone:
Calendar c = Calendar.getInstance();
c.setTime(new Date());
// get the current instant in UTC timestamp
Instant now = DateTimeUtils.toInstant(c);
// convert to some timezone
ZonedDateTime z = now.atZone(ZoneId.of("Europe/Berlin"));
// today is 08/06/2017, so Berlin is in DST (GMT+2)
System.out.println(z); // 2017-06-08T14:11:58.608+02:00[Europe/Berlin]
// testing with a date in January (not in DST, GMT+1)
System.out.println(z.withMonth(1)); // 2017-01-08T14:11:58.608+01:00[Europe/Berlin]
I've just picked some timezone that uses Central Europe timezone (Europe/Berlin): you can't use those 3-letter abbreviations, because they are ambiguous and not standard. You can change the code to the timezone that suits best for your system (you can get a list of all available timezones with ZoneId.getAvailableZoneIds()).
I prefer this solution because it's explicit what timezone we're using to display to the user (Date and Calendar's toString() methods use the default timezone behind the scenes and you never know what they're doing).
And internally, we can keep using the Instant, which is in UTC, so it's not affected by timezones (and you can always convert to and from timezones whenever you need) - if you want to convert the ZonedDateTime back to an Instant, just use the toInstant() method.
Actually, if you want to get the current date/time, just forget the old classes (Date and Calendar) and use just the Instant:
// get the current instant in UTC timestamp
Instant now = Instant.now();
But if you still need to use the old classes, just use DateTimeUtils to do the conversions.
The output of the examples above are the result of the ZonedDateTime.toString() method. If you want to change the format, use the org.threeten.bp.format.DateTimeFormatter class (take a look at the javadoc for more details about all the possible formats):
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss z X");
// DST (GMT+02)
System.out.println(formatter.format(z)); // 08/06/2017 14:11:58 CEST +02
// not DST (GMT+01)
System.out.println(formatter.format(z.withMonth(1))); // 08/01/2017 14:11:58 CET +01
Use ZonedDateTime class from JDK 8 java.time. It accommodates the Daylight Saving Time changes.
Refer the details at : https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html

Working with various Calendar TimeZone in Java (without using Joda Time)

I was looking for a way to get current time in various timezones based on an user input. I know I could use Joda Time! but is that the only way?
Isn't there an option in Java for doing this? I tried the following code which gives the same output for all 3 sysouts.
Calendar pst = Calendar.getInstance(TimeZone.getTimeZone("PST"));
System.out.println("PST " + pst.getTime());
Calendar ist = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
System.out.println("IST " + ist.getTime());
Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("Etc/UTC"));
System.out.println("UCT " + utc.getTime());
What am I missing here to get current time in other timezones?
Yes, that would show the same value in every case (or milliseconds apart) because the three calendars all refer to the same instant in time (execution time notwithstanding) and that's all that a java.util.Date represents. That's the result of Calendar.getTime().
However, the Calendar itself does know about time zones, and that will be reflected when you use Calendar.get etc. It will also be used when you use a SimpleDateFormat, where you can specify a particular time zone.
// Specify whatever format you want - bear in mind different locales etc
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(calendar.getTimeZone());
String text = format.format(calendar.getTime());
It's not clear exactly what you're trying to do, but basically you need to be aware of which types are time zone aware, and which aren't. It's really important to understand that a java.util.Date doesn't have a format, a calendar system or a time zone: it's just the number of milliseconds since the Unix epoch.
As Jon pointed out the method getTime() is returning a java.util.Date object which is just a millisecond value and not timezone aware.
If you are just looking at printing the times then you can use the calendar and manually get the fields you want like
System.out.println(utc.get(Calendar.HOUR_OF_DAY) + ":" + utc.get(Calendar.MINUTE))
This would need some formatting for a minute < 10 to display the 0
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
Instant now = Instant.now();
System.out.println(now);
ZonedDateTime zdtLos = now.atZone(ZoneId.of("America/Los_Angeles"));
ZonedDateTime zdtIndia = now.atZone(ZoneId.of("Asia/Kolkata"));
ZonedDateTime zdtUtc = now.atZone(ZoneOffset.UTC);
System.out.println(zdtLos);
System.out.println(zdtIndia);
System.out.println(zdtUtc);
}
}
Output from a sample run:
2021-07-26T12:39:17.413671-07:00[America/Los_Angeles]
2021-07-27T01:09:17.413671+05:30[Asia/Kolkata]
2021-07-26T19:39:17.413671Z
ONLINE DEMO
An Instant represents an instantaneous point on the timeline, normally represented in UTC time. The Z in the output is the timezone designator for a zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).
For any reason, if you need to convert this object of Instant to an object of java.util.Date, you can do so as follows:
Date date = Date.from(instant);
Learn more about the modern Date-Time API from Trail: Date Time.
Never use the 3-letter abbreviated timezone ID
Given below is an excerpt from the documentation page of TimeZone:
For compatibility with JDK 1.1.x, some other three-letter time zone
IDs (such as "PST", "CTT", "AST") are also supported. However, their
use is deprecated because the same abbreviation is often used for
multiple time zones (for example, "CST" could be U.S. "Central
Standard Time" and "China Standard Time"), and the Java platform can
then only recognize one of them.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

How to save DateTime as Date with TimeZone offset included?

I have some DateTime including TimeZone Europe/Vienna (+0200). It is fetched by this method:
settlementService.getPendingPeriodStart()
and look with toString like this:
2012-06-01T00:00:00.000+02:00
Now I want to save this date 2012-06-01 as java.util.Date, so I tried something like this:
transactionDate = settlementService.getPendingPeriodStart().withTime(0, 0, 0, 0).toDate();
But the result is this:
Thu May 31 22:00:00 UTC 2012
What's the best way to save the DateTime result as Date including the TimeZone offset, so transactionDate should be 2012-06-01. I could tinker with GregorianCalendar, but that's not what I like. This ought to be easier, isn't it?
By the way (if this isn't clear). The local system runs on UTC. That's why the result is Thu May 31 22:00:00 UTC 2012.
Unfortunately, the accepted answer is misguiding. As a matter of fact,
2012-06-01T00:00:00.000+02:00 = 2012-05-31T22:00:00Z
The Z on the right-hand side is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).
Writing 2012-06-01T00:00:00.000+02:00 as 2012-06-01, although a matter of just a function call, is dangerous for any business logic that depends on the timezone because it may have a different date in a timezone with a different offset value e.g. as shown above. 2012-06-01 is just a LocalDate which should be used to track events like birth date, wedding date etc.
java.time
The legacy date-time API (java.util date-time types and their formatting type, SimpleDateFormat etc.) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
Also, quoted below is a notice at the Home Page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern API:
How to parse the given date-time string:
The given date-time string has a timezone offset and therefore it should be parsed to OffsetDateTime. Since the modern date-time API is based on ISO 8601 and does not require using a DateTimeFormatter object explicitly as long as the date-time string conforms to the ISO 8601 standards.
OffsetDateTime odt = OffsetDateTime.parse("2012-06-01T00:00:00.000+02:00"); // 2012-06-01T00:00+02:00
How to get the date-time out of it in UTC:
There are multiple ways. The simplest way is to convert it into an Instant which represents an instantaneous point on the timeline which is in UTC.
Instant instant = odt.toInstant(); // 2012-05-31T22:00:00Z
Alternatively,
OffsetDateTime odtUtc = odt.withOffsetSameInstant(ZoneOffset.UTC); // 2012-05-31T22:00Z
How to get java.util.Date out of it:
If at all, you need an instance of java.util.Date from the instance of OffsetDateTime, you can use Date#from(Instant instant).
Date date = Date.from(instant); // Thu May 31 23:00:00 BST 2012 <--In my timezone
Note that a java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). When you print an object of java.util.Date, its toString method returns the date-time in the JVM's timezone, calculated from this milliseconds value. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFormat and obtain the formatted string from it e.g.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
System.out.println(sdf.format(date)); // 2012-05-31T22:00:00.000Z
How to get the date part out of it:
As I have already explained, it is dangerous for any business logic that depends on the timezone. However, it's just a matter of a simple function call.
LocalDate localDate = odt.toLocalDate(); // 2012-06-01
Learn more about java.time, the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
A date and the time zone of the user are 2 different things. One is a date, the other is a preference, or a presentation parameter.
Don't try to store them in the same field.
Consider that it wouldn't be even possible to store them together efficiently (without losing precision) as a date can be stored in a long only because it's specified that it's an UTC date.
You can save the time zone as an offset (a frequent recommendation is to keep the minutes in this offset ([hh]:[mm]) because of very small cases).
I think I found a solution. (If you know a better solution, just let me know)
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
DateTime dateTimeWithTimeZone = new DateTime(DateTimeZone.forID("Europe/Vienna")).withDate(2012, 06, 01).withTime(0, 0, 0, 0);
Date dateWithTimeZoneIncluded = dateTimeWithTimeZone.toLocalDate().toDate();
System.out.println(dateFormat.format(dateWithTimeZoneIncluded));
The result is 2012-06-01 as expected.

android java time

i'm building an android application which have a chat.
in this chat i each message to have its time sent signature.
my question is as follow:
lets say that the time in my country is X. my friend is abroad and his time is X minus 7 hours.
i'm sending him a message at 16:00 local time.
i want to avoid the situation that he will get at 09:00 a message which it signature will be 16:00 (which is a time in future if you're looking in the eyes of that friend in his country).
is there a way that in my phone the message will be written as 16:00 and in his phone it will be written as 09:00 ? i there a way to convert a time to a local time ?
System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. Date object does not save your local timezone.
You can use DateFormats to convert Dates to Strings in any timezone:
DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());
linked response
You should keep all time communications using UTC time. Then localize it for display based on the devices current timezone setting.
Use a long to save your time information as milliseconds since "epoch" (which is January 1, 1970, 00:00:00 GMT). It can be retreived with the Date.getTime() method and new Date objects are easily created using the Date(long millis) constructor. The Date objects are then displayed using the local timezone settings on each device.
EDIT:
Epoch is a defined point in time which is expressed differently in different time zones: 1970-01-01 00:00:00 GMT but
1969-12-31 19:00:00 EST. The timestamp is just the number of milliseconds elapsed since that time. So, for example the timestamp 1341169200 corresponds to 2012-07-01 19:00:00 GMT and 2012-07-01 14:00:00 EST.
You will need to save the time zone which your message will be saved in, and transfer it (or send the unix epoch time) and then on the other side make sure you read it in with the Locale time (using the Android documentation for things like http://developer.android.com/reference/java/util/Calendar.html can help).
Take a look at the answer over here:
https://stackoverflow.com/a/6094475/346232
You need to change the time to UTC and then convert on the device to the timezone.
Avoid java.util.Date/.Calendar
The java.util.Date/.Calendar classes bundled with Java (and Android) are notoriously troublesome, flawed in both design and implementation.
Joda-Time
The Joda-Time library is the way to go. This library inspired the java.time package now built into Java 8 (not available on Android).
UTC
As other answers suggested, the best practice (generally) is to keep your business logic and data storage/communication in UTC time zone (which some think of as no time zone or an "anti" time zone). Adjust to a specific time zone only when expected by the user or data-consumer.
Time Zone
The DateTime class in Joda-Time represents a date-time value along with an assigned time zone.
Note that it is best to specify a time zone in all your operations. Otherwise you will be implicitly relying on the JVM’s current default time zone. This is risky because that zone can change – even at runtime at any moment by any code in any thread of any app running within your app’s JVM. And use proper time zone names, never the 3-4 letter codes.
Example Code
Example code in Joda-Time 2.7.
DateTime sent = DateTime.now( DateTimeZone.getDefault() ) ;
DateTime sentUtc = nowMine.withZone( DateTimeZone.UTC ) ; // Generally, use this for your work, including communicating to other threads and apps and such.
When ready to display to the other user, adjust to the expected time zone.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ; // Or DateTimeZone.getDefault() if you want to rely on their JVM’s current default. To be absolutely sure of expected time zone, you really must ask the user.
DateTime sentMontréal = sentUtc.withZone( zone );
To generate a textual representation of those date-time objects, search the many Questions and Answers on StackOverflow.com on that subject. Search for terms like "joda" and "DateTimeFormatter" and "DateTimeFormat".

Categories

Resources