Generating UTC Time in java - java

I want to get the UTC time for 01/01/2100 in Java to '2100-01-01 00:00:00'. I am getting "2100-01-01 00:08:00". Any idea, how to correct this.
public Date getFinalTime() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date finalTime = null;
try
{
finalTime = df.parse("01/01/2100");
} catch (ParseException e)
{
e.printStackTrace();
}
calendar.setTime(finalTime);
return calendar.getTime();
}

You need to specify the time zone for the SimpleDateFormat as well - currently that's parsing midnight local time which is ending up as 8am UTC.
TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(utc);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setTimeZone(utc);
Date finalTime = null;
try
{
finalTime = df.parse("01/01/2100");
} catch (ParseException e)
{
e.printStackTrace();
}
calendar.setTime(finalTime);
As ever though, I would personally recommend using Joda Time which is far more capable in general. I'd be happy to translate your example into Joda Time if you want.
Additionally, I see you're returning calendar.getTime() - that's just the same as returning finalTime as soon as you've computed it.
Finally, just catching a ParseException and carrying on as if it didn't happen is a very bad idea. I'm hoping this is just sample code and it doesn't reflect your real method. Likewise I'm assuming that really you'll be parsing some other text - if you're not, then as Eyal said, you should just call methods on Calendar directly. (Or, again, use Joda Time.)

You need to set the time zone of the SimpleDateFormat object as well, otherwise it assumes the default time zone.
Anyway, it seems like using only a Calendar is enough in your case. Use its setters to set the right values for all fields (year, month, day, hour, etc), and then retrieve the 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 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:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDate = "01/01/2100";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("d/M/u", Locale.ENGLISH);
ZonedDateTime zdt = LocalDate.parse(strDate, dtfInput)
.atStartOfDay(ZoneId.of("Etc/UTC"));
// Default format
System.out.println(zdt);
// Getting and displaying LocalDateTime
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
// A custom format
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
// Alternatively dtfOutput.format(ldt);
String formatted = dtfOutput.format(zdt);
System.out.println(formatted);
// Converting to some other types
OffsetDateTime odt = zdt.toOffsetDateTime();
Instant instant = zdt.toInstant();
System.out.println(odt);
System.out.println(instant);
}
}
Output:
2100-01-01T00:00Z[Etc/UTC]
2100-01-01T00:00
2100-01-01 00:00:00
2100-01-01T00:00Z
2100-01-01T00:00:00Z
ONLINE DEMO
The Z in the output 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).
Note: The Date-Time without timezone name or timezone offset should be represented by LocalDateTime (which is used for events that are normally not represented with timezone information). In this sense, LocalDateTime is useless in this case and you should use ZonedDateTime itself or Instant or OffsetDateTime. I recommend you also check this answer and this answer if you are dealing with JDBC.
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.

java.time
Like Arvind Kumar Avinash I very clearly recommend that you use java.time, the modern Java date and time API, for your date and time work. If what you want is a fixed (constant) date and time, use OffsetDateTime.of().
OffsetDateTime finalTime = OffsetDateTime.of(2100, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
System.out.println(finalTime);
Output:
2100-01-01T00:00Z
The trailing Z means UTC.
Tutorial link
Oracle tutorial: Date Time explaining how to use java.time.

TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(utc);
DateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
dateformat.setTimeZone(utc);
Timezone needs to be set.

Related

get the day of the year as an integer in Kotlin Android Studio

I am trying to get the current day of the year as an integer to access within my program. I looked at the Kotlin Docs and found a function called getDay(), but when I type it into my program it gives me an error and says the function is not defined. I am using Android Studio with Kotlin and the minimum API is 21.
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*.
Solution using java.time, the modern Date-Time API:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Note: If you want to work with a specific timezone, use LocalDate.now(ZoneId)
// e.g. LocalDate.now(ZoneId.of("Australia/Brisbane")) or
// LocalDate.now(ZoneOffset.UTC) etc.
LocalDate today = LocalDate.now();
int doy = today.getDayOfYear();
System.out.println(doy);
// Using DateTimeFormatter (not recommended for production code)
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("D", Locale.ENGLISH);
String strDoy = today.format(dtf);
System.out.println(strDoy);
}
}
Output in my timezone, Europe/London:
289
289
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
For any reason, if you want to use the legacy API:
A java.util.Date object 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. To get the String representation of the java.util.Date object in a different format and timezone, you need to use SimpleDateFormat with the desired format and the applicable timezone e.g.
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String strDateNewYork = sdf.format(date);
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String strDateUtc = sdf.format(date);
Let's see why knowing the above fact is important:
The function, Calendar#getInstance returns a calendar based on the current time in the default time zone with the default FORMAT locale. If you want to find some information from it for some other timezone, you have two options:
Change the default timezone e.g. TimeZone.setDefault(TimeZone.getTimeZone("Australia/Brisbane")). However, this may result in other parts of the application behave incorrectly. Therefore, this option is strongly discouraged.
Format the java.util.Date (which you can get via Calendar#getTime) using SimpleDateFormat set with the required timezone shown above.
Demo:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("D");
// For the JVM's timezone
sdf.setTimeZone(TimeZone.getDefault());
System.out.println(sdf.format(now));
// For the timezone, UTC
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(now));
// For the timezone, Australia/Brisbane
sdf.setTimeZone(TimeZone.getTimeZone("Australia/Brisbane"));
System.out.println(sdf.format(now));
System.out.println();
}
}
Output in my timezone, Europe/London at the time of posting this answer:
289
289
290
ONLINE DEMO
* 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. Note that Android 8.0 Oreo already provides support for java.time.
If you perform desugaring in order to be able to use Java 8 Time API back to API 21, you can then use this method to get the day of year
import java.time.LocalDate
val dayOfYear = LocalDate.now().dayOfYear
System.out.println(dayOfYear);
Answer: 289
Date().getDay() or rather Date().day in Kotlin returns the day of the week so not what you want.
Calendar.getInstance().get(Calendar.DAY_OF_YEAR) is the correct function to use in Android. It returns a calendar using the default time zone and locale. The Calendar returned is based on the current time in the default time zone with the default FORMAT locale (https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--).
Calendar, Date etc. have been replaced by new java.time classes with Java 8 so you should use LocalDate.now().dayOfYear but as #nuhkoca indicates in order to do that you need to enable Java 8+ API desugaring support which is basically adding this to your build file (Kotlin DSL not Groovy):
compileOptions {
isCoreLibraryDesugaringEnabled = true
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
dependencies {
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:1.1.5")
try this code :
import java.time.LocalDate
import java.util.*
fun main() {
val cal = Calendar.getInstance()
val day = cal[Calendar.DATE]
val doy = cal[Calendar.DAY_OF_YEAR]
println("Current Date: " + cal.time)
println("Day : $day")
println("Day of Year : $doy")
}

How to convert UTC formatted string to calendar in specific timezone?

I'm trying to convert some string that is in UTC time to a java Calendar object that should be set to GMT-5.
My current UTC string input is this:
UTC date : 20050329174411
I use this code (I detect the 'pattern' as shown below):
DateFormat dateFormat = new SimpleDateFormat(pattern);
Date date = dateFormat.parse(utcDate);
calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT-5"));
calendar.setTime(date);
I then printed the time like this:
calendar.getTime()
And I got this result:
GMT date : Tue Mar 29 17:44:11 EST 2005
I need to support theses date/time string patterns:
FORMAT_UTC4 = "yyyy";
FORMAT_UTC6 = "yyyyMM";
FORMAT_UTC8 = "yyyyMMdd";
FORMAT_UTC10 = "yyyyMMddHH";
FORMAT_UTC12 = "yyyyMMddHHmm";
FORMAT_UTC14 = "yyyyMMddHHmmss";
I would be expecting the time to be set to "12:44:11". I have read a couple of examples and I find date time handling pretty confusing. For me, it's always the same, I get some sort of string formatted UTC and I convert it to GMT-5. I really feel it should be easy!
Ref 1 : How can I get the current date and time in UTC or GMT in Java?
Ref 2 : How to handle calendar TimeZones using Java?
You must set the SimpleDateFormat's time zone to UTC before parsing the date. Else, it uses your default timezone.
And to display the date in the "GMT-5" timezone, you should use another DateFormat, with the timezone set to GMT-5, and format the date with this DateFormat. The toString() method of Date uses your default time zone to transform the date into something readable.
java.time
Note that GMT-5 or timezone offset of -05:00 hours is a fixed offset i.e. independent of the DST and type to represent a date-time with timezone offset is OffsetDateTime.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.ofEpochMilli(20050329174411L);
OffsetDateTime odt = instant.atOffset(ZoneOffset.of("-05:00"));
// Alternatively
// OffsetDateTime.ofInstant(instant, ZoneOffset.of("-05:00"));
System.out.println(odt);
}
}
Output:
2605-05-15T18:52:54.411-05:00
If you are looking for an automatic adjustment of timezone offset as per the DST, use ZonedDateTime.
Demo:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.ofEpochMilli(20050329174411L);
ZonedDateTime zdt = instant.atZone(ZoneId.of("America/Chicago"));
// Alternatively
// ZonedDateTime.ofInstant(instant, ZoneId.of("America/Chicago"));
System.out.println(zdt);
}
}
Output:
2605-05-15T18:52:54.411-05:00[America/Chicago]
Learn more about java.time, the modern date-time API* from Trail: Date Time.
If at all you need an object of java.util.Calendar from this object of ZonedDateTime, you can do so as follows:
Calendar calendar = Calendar.getInstance();
calendar.setTime(Date.from(zdt.toInstant()));
* 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.

Get only the date from the timestamp

This is my Below function in which I am passing timestamp, I need only the date in return from the timestamp not the Hours and Second. With the below code I am getting-
private String toDate(long timestamp) {
Date date = new Date (timestamp * 1000);
return DateFormat.getInstance().format(date).toString();
}
This is the output I am getting.
11/4/01 11:27 PM
But I need only the date like this
2001-11-04
Any suggestions?
Use SimpleDateFormat instead:
private String toDate(long timestamp) {
Date date = new Date(timestamp * 1000);
return new SimpleDateFormat("yyyy-MM-dd").format(date);
}
Updated: Java 8 solution:
private String toDate(long timestamp) {
LocalDate date = Instant.ofEpochMilli(timestamp * 1000).atZone(ZoneId.systemDefault()).toLocalDate();
return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
You can use this code to get the required results
protected Timestamp timestamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
protected String today_Date=timestamp.toString().split(" ")[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:
You can use Instant#ofEpochSecond to get an Instant out of the given timestamp and then use LocalDate.ofInstant to get a LocalDate out of the obtained Instant.
Demo:
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(toDate(1636120105L));
}
static LocalDate toDate(long timestamp) {
return LocalDate.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.systemDefault());
}
}
Output:
2021-11-05
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time. Check this answer and this answer to learn how to use java.time API with JDBC.
* 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. Note that Android 8.0 Oreo already provides support for java.time.
Joda-Time
The Joda-Time library offers a LocalDate class to represent a date-only value without any time-of-day nor time zone.
Time Zone
Determining a date requires a time zone. A moment just after midnight in Paris means a date that is a day ahead of the same simultaneous moment in Montréal. If you neglect to specify a time zone, the JVM’s current default time zone is applied – probably not what you want as results may vary.
Example Code
long millisecondsSinceUnixEpoch = ( yourNumberOfSecondsSinceUnixEpoch * 1000 ); // Convert seconds to milliseconds.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
LocalDate localDate = new LocalDate( millisecondsSinceUnixEpoch, timeZone );
String output = localDate.toString(); // Defaults to ISO 8601 standard format, YYYY-MM-DD.
Previous Day
To get the day before, as requested in a comment.
LocalDate dayBefore = localDate.minusDays( 1 );
Convert to j.u.Date
The java.util.Date & .Calendar classes should be avoided as they are notoriously troublesome. But if required, you may convert.
java.util.Date date = localDate.toDate(); // Time-of-day set to earliest valid for that date.

Java.util.Date: try to understand UTC and ET more

I live in North Carolina, btw, which is on the East Side. So I compile and run this code and it print out the same thing. The documentation say that java.util.date try to reflect UTC time.
Date utcTime = new Date();
Date estTime = new Date(utcTime.getTime() + TimeZone.getTimeZone("ET").getRawOffset());
DateFormat format = new SimpleDateFormat("dd/MM/yy h:mm a");
System.out.println("UTC: " + format.format(utcTime));
System.out.println("ET: " + format.format(estTime));
And this is what I get
UTC: 11/05/11 11:14 AM
ET: 11/05/11 11:14 AM
But if I go to this website which try to reflect all different time, UTC and ET are different. What did I do wrong here
That's because getRawOffset() is returning 0 - it does that for me for "ET" as well, and in fact TimeZone.getTimeZone("ET") basically returns GMT. I suspect that's not what you meant.
The best Olson time zone name for North Carolina is "America/New_York", I believe.
Note that you shouldn't just add the raw offset of a time zone to a UTC time - you should set the time zone of the formatter instead. A Date value doesn't really know about a time zone... it's always just milliseconds since January 1st 1970 UTC.
So you can use:
import java.text.;
import java.util.;
Date date = new Date();
DateFormat format = new SimpleDateFormat("dd/MM/yy h:mm a zzz");
format.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println("Eastern: " + format.format(date));
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
System.out.println("UTC: " + format.format(date));
Output:
Eastern: 11/05/11 11:30 AM EDT
UTC: 11/05/11 3:30 PM UTC
I'd also recommend that you look into using java.time now - which is much, mnuch better than the java.util classes.
according this post you habe to write TimeZone.getTimeZone("ETS") instead of TimeZone.getTimeZone("ET")
TimeZone.getTimeZone("ET").getRawOffset() is returning 0 this is why
The time zone you're looking for is "EST" or "EDT" (for Daylight time), not "ET". See http://mindprod.com/jgloss/timezone.html.
The proper abbreviation for Eastern Standard Time is "EST", not "ET". It looks like the getRawOffset() method returns 0 if it is passed an unknown time zone.
TimeZone.getTimeZone("EST").getRawOffset()
Also, when you output the utcTime variable, you are not outputting the UTC time. You are outputting EST time because you live in that timezone. From what I understand, the Date class internally stores the time in UTC...but when you format it in order to output it as a human-readable string, it takes the current locale/timezone into account.
Unknowingly, you have introduced two major problems in your code:
Not using the proper timezone name: The two/three/four letter timezone names (e.g. ET, EST, CEST etc.) are error-prone. The proper way of naming a timezone is Region/City e.g. Europe/London. In most cases, the Region is the name of the continent to which the City belongs.
Not using Locale with SimpleDateFormat: A parsing/formatting type e.g. the legacy, SimpleDateFormat or the modern, DateTimeFormatter are Locale-sensitive and therefore you should always use a Locale to avoid surprises. You can check this answer to learn more about it.
Also, 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). Since it does not hold any format and timezone information, it applies the format, EEE MMM dd HH:mm:ss z yyyy and the JVM's timezone to return the value of Date#toString derived from this milliseconds value. If you need to print the Date-Time in a different format and timezone, you will need to use a SimpleDateFormat with the desired format and the applicable timezone e.g.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy hh:mm a zzz", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println(sdf.format(date));
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
System.out.println(sdf.format(date));
}
}
A sample output:
05/06/21 08:29 AM EDT
05/06/21 12:29 PM UTC
ONLINE DEMO
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*.
A demo using java.time, the modern API:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
Instant now = Instant.now();
System.out.println(now);
ZonedDateTime zdtUTC = now.atZone(ZoneId.of("Etc/UTC"));
System.out.println(zdtUTC);
ZonedDateTime zdtNewYork = now.atZone(ZoneId.of("America/New_York"));
System.out.println(zdtNewYork);
}
}
A sample output:
2021-06-05T12:19:58.092338Z
2021-06-05T12:19:58.092338Z[Etc/UTC]
2021-06-05T08:19:58.092338-04:00[America/New_York]
ONLINE DEMO
Need output string in a different format?
You can use DateTimeFormatter for the output string in a different format e.g.
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Instant now = Instant.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/uu hh:mm a zzz", Locale.ENGLISH);
ZonedDateTime zdtUTC = now.atZone(ZoneId.of("Etc/UTC"));
System.out.println(dtf.format(zdtUTC));
ZonedDateTime zdtNewYork = now.atZone(ZoneId.of("America/New_York"));
System.out.println(dtf.format(zdtNewYork));
}
}
A sample output:
05/06/21 12:34 PM UTC
05/06/21 08:34 AM EDT
ONLINE DEMO
Here, you can use yy instead of uu but I prefer u to y.
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.

Output RFC 3339 Timestamp in Java

I want to output a timestamp with a PST offset (e.g., 2008-11-13T13:23:30-08:00). java.util.SimpleDateFormat does not seem to output timezone offsets in the hour:minute format, it excludes the colon. Is there a simple way to get that timestamp in Java?
// I want 2008-11-13T12:23:30-08:00
String timestamp = new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssZ").format(new Date());
System.out.println(timestamp);
// prints "2008-11-13T12:23:30-0800" See the difference?
Also, SimpleDateFormat cannot properly parse the example above. It throws a ParseException.
// Throws a ParseException
new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssZ").parse("2008-11-13T13:23:30-08:00")
Starting in Java 7, there's the X pattern string for ISO8601 time zone. For strings in the format you describe, use XXX. See the documentation.
Sample:
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
.format(new Date()));
Result:
2014-03-31T14:11:29+02:00
Check out the Joda Time package. They make RFC 3339 date formatting a lot easier.
Joda Example:
DateTime dt = new DateTime(2011,1,2,12,45,0,0, DateTimeZone.UTC);
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
String outRfc = fmt.print(dt);
From the "get it done dept," one solution is to use regexes to fix up the string after SimpleDateFormat has completed. Something like s/(\d{2})(\d{2})$/$1:$2/ in Perl.
If you are even remotely interested in this, I will edit this response with the working Java code.
But, yeah. I am hitting this problem too. RFC3339, I'm looking at you!
EDIT:
This works for me
// As a private class member
private SimpleDateFormat rfc3339 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String toRFC3339(Date d)
{
return rfc3339.format(d).replaceAll("(\\d\\d)(\\d\\d)$", "$1:$2");
}
I spent quite a lot of time looking for an answer to the same issue and I found something here : http://developer.android.com/reference/java/text/SimpleDateFormat.html
Suggested answer:
String timestamp = new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssZZZZZ").format(new Date());
If you notice I am using 5 'Z' instead of one. This gives the output with a colon in the offset like this: "2008-11-13T12:23:30-08:00". Hope it helps.
The problem is that Z produces the time zone offset without a colon (:) as the separator.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'h:m:ss.SZ");
Is not what exactly you need?
We can simply use ZonedDateTime class and DateTimeFormatter class for this.
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx");
ZonedDateTime z2 = ZonedDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS);
System.out.println("format =======> " + z2.format(format));
Output: format =======> 30-03-2020T05:57:37+00:00
I found a stray PasteBin that helped me out with the issue: http://pastebin.com/y3TCAikc
Just in case its contents later get deleted:
// I want 2008-11-13T12:23:30-08:00
String timestamp = new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssZ").format(new Date());
System.out.println(timestamp);
// prints "2008-11-13T12:23:30-0800" See the difference?
// Throws a ParseException
new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssZ").parse("2008-11-13T13:23:30-08:00")
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'h:m:ss.SZ");
I made a InternetDateFormat class for RFC3339.
But source code comment is Japanese.
PS:I created English edition and refactoring a little.
i tried this format and worked for me yyyy-MM-dd'T'HH:mm:ss'Z'
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: The largest city in the Pacific Time Zone is Los Angeles whose timezone name is America/Los_Angeles. Using ZoneId.of("America/Los_Angeles"), you can create an instance of ZonedDateTime which has been designed to adjust the timezone offset automatically on DST transitions.
If you need timezone offset but not the timezone name, you can convert a ZonedDateTime into OffsetDateTime using ZonedDateTime#toOffsetDateTime. Some other uses of OffsetDateTime are to create a Date-Time instance with a fixed timezone offset (e.g. Instant.now().atOffset(ZoneOffset.of("+05:30")), and to parse a Date-Time string with timezone offset.
Demo:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
ZoneId zoneIdLosAngeles = ZoneId.of("America/Los_Angeles");
ZonedDateTime zdtNowLosAngeles = ZonedDateTime.now(zoneIdLosAngeles);
System.out.println(zdtNowLosAngeles);
// With zone offset but without time zone name
OffsetDateTime odtNowLosAngeles = zdtNowLosAngeles.toOffsetDateTime();
System.out.println(odtNowLosAngeles);
// Truncated up to seconds
odtNowLosAngeles = odtNowLosAngeles.truncatedTo(ChronoUnit.SECONDS);
System.out.println(odtNowLosAngeles);
// ################ A winter date-time ################
ZonedDateTime zdtLosAngelesWinter = ZonedDateTime
.of(LocalDateTime.of(LocalDate.of(2021, 11, 20), LocalTime.of(10, 20)), zoneIdLosAngeles);
System.out.println(zdtLosAngelesWinter); // 2021-11-20T10:20-08:00[America/Los_Angeles]
System.out.println(zdtLosAngelesWinter.toOffsetDateTime()); // 2021-11-20T10:20-08:00
// ################ Parsing a date-time string with zone offset ################
String strDateTime = "2008-11-13T13:23:30-08:00";
OffsetDateTime odt = OffsetDateTime.parse(strDateTime);
System.out.println(odt); // 2008-11-13T13:23:30-08:00
}
}
Output from a sample run:
2021-07-18T03:27:15.578028-07:00[America/Los_Angeles]
2021-07-18T03:27:15.578028-07:00
2021-07-18T03:27:15-07:00
2021-11-20T10:20-08:00[America/Los_Angeles]
2021-11-20T10:20-08:00
2008-11-13T13:23:30-08:00
ONLINE DEMO
You must have noticed that I have not used a DateTimeFormatter to parse the Date-Time string of your question. It is because your Date-Time string is compliant with ISO-8601 standards. 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.
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.
I tested a lot with this one, works well for me... In particular when it comes to parsing (and for formatting too), it is the closest I have found so far
DateTimeFormatter rfc3339Formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
DateTimeFormatter rfc3339Parser = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendValue(ChronoField.YEAR, 4)
.appendLiteral('-')
.appendValue(ChronoField.MONTH_OF_YEAR, 2)
.appendLiteral('-')
.appendValue(ChronoField.DAY_OF_MONTH, 2)
.appendLiteral('T')
.appendValue(ChronoField.HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(ChronoField.MINUTE_OF_HOUR, 2)
.appendLiteral(':')
.appendValue(ChronoField.SECOND_OF_MINUTE, 2)
.optionalStart()
.appendFraction(ChronoField.NANO_OF_SECOND, 2, 9, true) //2nd parameter: 2 for JRE (8, 11 LTS), 1 for JRE (17 LTS)
.optionalEnd()
.appendOffset("+HH:MM","Z")
.toFormatter()
.withResolverStyle(ResolverStyle.STRICT)
.withChronology(IsoChronology.INSTANCE);
Test cases at https://github.com/guyplusplus/RFC3339-DateTimeFormatter

Categories