I have the following code:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CalendarTest {
public static void main(String[] args) {
try {
Calendar calendar = Calendar.getInstance();
Date _date = new SimpleDateFormat("ddMMyyyy").parse("13102014");
Date _time = new SimpleDateFormat("hhmmss").parse("201100");
calendar.setTimeInMillis(_date.getTime() + _time.getTime());
System.out.println(calendar.getTime()); // NOK 1 hour less
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Why does it produce:
Mon Oct 13 19:11:00 CEST 2014
Instead of:
Mon Oct 13 20:11:00 CEST 2014
UTC versus DST
Because java.util.Date works in UTC. But its toString method confusingly applies your JVM’s current default time zone when generating a String representation of the date-time value.
I imagine your JVM’s current default time zone is in Daylight Saving Time (DST), thus the hour adjustment.
24-Hour Time
Also, your hour-of-day code should be HH for 24-hour time, not hh for 12-hour time.
When you parse only the time on a separate line from the date, it treats it as though that time occurs on Jan 1st 1970. Which is in the winter when you are on standard time. So when you combine the two together you get a value that's in standard time, one hour behind the current clock-on-the-wall time which is in Daylight time.
I would say that it's possible to produce the desired output with a simple change. No JODA or Java 8 needed. I don't understand why you wrote it the way you did.
package cruft;
/**
* CalendarTest description here
* #author Michael
* #link https://stackoverflow.com/questions/26348140/java-date-calendar-giving-different-results-as-expected
* #since 10/13/2014 4:16 PM
*/
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CalendarTest {
public static void main(String[] args) {
try {
Calendar calendar = Calendar.getInstance();
Date _date = new SimpleDateFormat("ddMMyyyy hhmmss").parse("13102014 201100");
calendar.setTimeInMillis(_date.getTime());
System.out.println(calendar.getTime());
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
Here's the output I get:
"C:\Program Files\Java\jdk1.7.0_45\bin\java" -Didea.launcher.port=7536 "
Mon Oct 13 20:11:00 EDT 2014
Process finished with exit code 0
Joda-Time
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use a competent date-time library instead. In Java that means either:
Joda-TimeThe venerable library used by many people for many years as a replacement for j.u.Date/Calendar.
java.timeBundled with Java 8, inspired by Joda-Time, defined by JSR-310, described in The Tutorial)
In Joda-Time, a DateTime object knows its own assigned time zone (unlike j.u.Date).
That string format in your Question is annoyingly bad. If possible, replace with ISO 8601 standard strings. The standard strings are much more readable and intuitive. Furthermore, both Joda-Time and java.time parse and generate standard strings by default.
Example code using Joda-Time 2.5. We do not know your time zone, so I am arbitrarily choosing Berlin. I assume your input string represents a moment in that time zone, though your Question is ambiguous.
Parse input string.
String input = "13102014201100";
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Berlin" );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "ddMMyyyyHHmmss" );
DateTimeFormatter formatterBerlin = formatter.withZone( timeZone );
DateTime dateTimeBerlin = formatterBerlin.parseDateTime( input );
Adjust to another time zone. In this case, UTC.
DateTime dateTimeUtc = dateTimeBerlin.withZone( DateTimeZone.UTC );
Dump to console.
System.out.println( "input: " + input );
System.out.println( "dateTimeBerlin: " + dateTimeBerlin );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run.
input: 13102014201100
dateTimeBerlin: 2014-10-13T20:11:00.000+02:00
dateTimeUtc: 2014-10-13T18:11:00.000Z
Related
I had to get the current date, add 20 years, and transferred it in an XML object.
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "XMLCommande", propOrder = {
...
"dateLivSouhaitee",
...
})
public class XMLCommande {
...
#XmlElement(name = "date_liv_souhaitee", required = true)
#XmlSchemaType(name = "date")
protected XMLGregorianCalendar dateLivSouhaitee;
...
}
No date format is specified, it's all by default :
XMLCommande xmlMessage = new XMLCommande();
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.add(Calendar.YEAR, 20);
ligne.setDateLivSouhaitee(DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar2));
The problem, is, for some unknown reason, that's sometimes I have a "Z" at the end of the date, but sometimes don't :
<date_liv_souhaitee>2041-05-26Z</date_liv_souhaitee>
<date_liv_souhaitee>2041-05-26+02:00</date_liv_souhaitee>
It's the same server, why sometimes I have the Z with "+02:00" and sometimes don't ?
How can I force the format to be always :
<date_liv_souhaitee>2041-05-26+02:00</date_liv_souhaitee>
The Z in the date-time string 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).
In the other case, you have +02:00 timezone offset added in the date-time string i.e. the corresponding date-time in UTC will be the given date-time minus 2 hours. You can convert the UTC date-time into date-time with +02:00 timezone offset e.g.
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class Main {
public static void main(String[] args) throws DatatypeConfigurationException {
ZonedDateTime zdtUtc = LocalDate.of(2041, 5, 26).atStartOfDay(ZoneOffset.UTC);
System.out.println(zdtUtc);
ZonedDateTime zdtOffsetTwoHrs = zdtUtc.withZoneSameInstant(ZoneOffset.of("+02:00"));
System.out.println(zdtOffsetTwoHrs);
GregorianCalendar gregorianCalendar = GregorianCalendar.from(zdtOffsetTwoHrs);
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(gregorianCalendar);
System.out.println(xmlGregorianCalendar);
}
}
Output:
2041-05-26T00:00Z
2041-05-26T02:00+02:00
2041-05-26T02:00:00.000+02:00
Why do I sometimes get the Z and sometimes +02:00?
If both come from creating a GregorianCalendar using the no-arg constructor and converting it to XMLGregorianCalendar, then the best explanation is that someone is modifying the default time zone of your JVM. A part of your own program may do that or some other program running in the same JVM. To demonstrate:
TimeZone.setDefault(TimeZone.getTimeZone(ZoneId.of("Europe/Paris")));
GregorianCalendar gc = new GregorianCalendar();
System.out.println(DatatypeFactory.newInstance().newXMLGregorianCalendar(gc));
TimeZone.setDefault(TimeZone.getTimeZone(ZoneOffset.UTC));
gc = new GregorianCalendar();
System.out.println(DatatypeFactory.newInstance().newXMLGregorianCalendar(gc));
Output from these code lines was:
2021-05-26T19:41:29.744+02:00
2021-05-26T17:41:29.776Z
new GregorianCalendar() creates a GregorianCalendar that has the default time zone of the JVM at the time of creation. As Arvind Kumar Avinash already explained, offset 0 from UTC is rendered as Z in accordance with the ISO 8601 standard.
How can I force +02:00 always?
I recommend that you use java.time, the modern Java date and time API, for your date work. The OffsetDateTime class represents a date and time with a UTC offset, so just set the offset to +2.
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.ofHours(2));
OffsetDateTime in20Years = now.plusYears(20);
String dateStringWithOffset0200 = in20Years.format(DateTimeFormatter.ISO_OFFSET_DATE);
System.out.println(dateStringWithOffset0200);
2041-05-26+02:00
If you do need an XMLGregorianCalendar, build one from the string we just got:
XMLGregorianCalendar xmlgc = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(dateStringWithOffset0200);
System.out.println(xmlgc);
2041-05-26+02:00
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
public static String convertInDateTimeSecondTOJodaTime(String dateTime) {
try {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
DateTime date = formatter.parseDateTime(dateTime).withZoneRetainFields(DateTimeZone.UTC);
return date.toString("h:mm aa");
} catch (Exception e) {
return null;
}
}
main(){
print(convertInDateTimeSecondTOJodaTime("2020-04-09T07:31:16Z"))
}
I am trying to convert given date-time in UTC format using joda date time it's giving wrong time it's given one hour before please help me what I am doing wrong.
The desired result is in London time, so 8:31 AM in this case.
import java.util.Date;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
public class CurrentUtcDate {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC Time is: " + dateFormat.format(date));
}
}
Output
UTC Time is: 22-01-2018 13:14:35
You can check here https://www.quora.com/How-do-I-get-the-current-UTC-date-using-Java
As you need to you use Joda DateTime, you need to use formatter of Joda.
You are returning date with pattern "h:mm aa" so I assume you need to extract time from the date.
Below code should work:
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class MyDateCoonverter {
public static void main(String a[]) {
System.out.println(convertInDateTimeSecondTOJodaTime("2020-04-09T07:31:16Z"));
}
public static String convertInDateTimeSecondTOJodaTime(String dateTime) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
DateTime dt = formatter.parseDateTime(dateTime);
return dt.toString("h:mm aa", Locale.ENGLISH);
}
}
It gives output as:
7:31 AM
If you don't want to use any third party library & still want to extract only time from date, you can use Java's LocalTime.
If you are using Java 8 or newer, you should not use java.util.Date (deprecated) or Joda Time (replaced by the new DATE API of Java 8 with java.time package) :
public static void main(String[] args) {
String date = "2020-04-09T07:31:16Z";
String formatedDate = ZonedDateTime.parse(date).format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT));
System.out.println(formatedDate); //print "7:31 AM"
}
}
First, don’t handle date and time as strings in your program. Handle them as proper date-time objects. So but for all but the simplest throw-away programs you should not want a method that converts from a string in UTC to a string in London time in a different format.
So when you accept string input, parse into a DateTime object:
String stringInput = "2020-04-09T07:31:16Z";
DateTime dt = DateTime.parse(stringInput);
System.out.println("Date-time is: " + dt);
Output so far is:
Date-time is: 2020-04-09T07:31:16.000Z
I am exploiting the fact that your string is in ISO 8601 format, the default for Joda-Time, so we need no explicit formatter for parsing it.
Not until you need to give string output, convert your date and time to the desired zone and format into the desired string:
DateTimeZone zone = DateTimeZone.forID("Europe/London");
DateTime outputDateTime = dt.withZone(zone);
String output = outputDateTime.toString("h:mm aa");
System.out.println("Output is: " + output);
Output is: 8:31 AM
What went wrong in your code
Z in single quotes in your format pattern string is wrong. Z in your input string is an offset of 0 from UTC and needs to be parsed as an offset, or you are getting an incorrect result. Never put those quotes around Z.
withZoneRetainFields() is the wrong method to use for converting between time zones. The method name means that the date and hour of day are kept the same and only the time zone changed, which typically leads to a different point in time.
What happened was that your string was parsed into 2020-04-09T07:31:16.000+01:00, which is the same point in time as 06:31:16 UTC, so wrong. You next substituted the time zone to UTC keeping the time of day of 07:31:16. This time was then formatted and printed.
Do consider java.time
As Fabien said, Joda-Time has later been replaced with java.time, the modern Java date and time API. The Joda-Time home page says:
Note that Joda-Time is considered to be a largely “finished” project.
No major enhancements are planned. If using Java SE 8, please migrate
to java.time (JSR-310).
Links
Wikipedia article: ISO 8601
Joda-Time home
I've been experimenting with different formats for a while now. But I encountered a problem when parsing a date string to a date.
Here's the sample date string I'm trying to parse. "2015-04-13T10:17:00-04:00"
Here's my code:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'-'hh:mm", Locale.ENGLISH);
try {
startCal.setTime(format.parse(data.StartTime));
endCal.setTime(format.parse(data.EndTime));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The value that I'm getting when printing it on the log is
Log.i("Event exact date", String.valueOf(startCal.getTime().toString()));
04-13 22:38:11.526: I/Event exact date(1665): Mon Apr 13 04:00:00 GMT+08:00 2015
I was expecting the hour value to be 10 and minutes to be 17. I think it is getting the value from the "-hh:mm". I'm getting this value from a web api. Any ideas guys? Thanks
I think the format you want is:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.ENGLISH);
Where the 'XXX', according to SimpleDateFormat API docs, means ISO 8601 time zone.
Full example:
public class TestDateParse {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.ENGLISH);
Date date = format.parse("2015-04-13T10:17:00-04:00");
System.out.println("date: " + date);
}
}
Test output:
date: Mon Apr 13 16:17:00 CEST 2015
If you not need "-04:00" zone offset (timezone) then just truncate string "2015-04-13T10:17:00-04:00" to "2015-04-13T10:17:00"
String fullDate = "2015-04-13T10:17:00-04:00";
String truncatedDate = fullDate.substring(0, fullDate.lastIndexOf('-'));
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",
Locale.ENGLISH);
try {
Date dte = format.parse(truncatedDate);
System.out.println("date=" + dte);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Result is:
date=Mon Apr 13 10:17:00 CEST 2015
use Z for timezone. It should work.
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
for reference, this is the documentation http://developer.android.com/reference/java/text/SimpleDateFormat.html
java.time
You are using troublesome old date-time classes. Avoid them.
Use the java.time framework built into Java 8 and later. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. Look for back-ports for Java 6 & 7 and for Android.
Your input string happens to be in standard ISO 8601 format. The java.time classes use ISO 8601 as their defaults when parsing/generating textual representations of date-time values. So no need to specify a formatting pattern.
Offset
That last part -04:00 is indeed an offset-from-UTC as mentioned in other Answers. It means the date-time shown is four hours behind UTC.
String input = "2015-04-13T10:17:00-04:00";
OffsetDateTime odt = OffsetDateTime.parse( input );
Time Zone
You can search the list of time zones to see which zones use that particular offset of -04:00. I see a few dozen zones with that offset.
If you know the intended time zone, apply it (a ZoneId). A time zone is an offset-from-UTC plus the rules for handling anomalies such as Daylight Saving Time (DST). So using a time zone is always better than a mere offset, provided you are certain of the correct zone.
ZoneId zoneId = ZoneId.of( "America/Puerto_Rico" );
ZonedDateTime zdt = odt.atZoneSameInstant( zoneId );
UTC
The OffsetDateTime and ZonedDateTime objects seen above represent the very same moment on the timeline. If you want to see that moment in UTC, as for an Instant.
Instant instant = odt.toInstant(); // …or…
Instant instant = zdt.toInstant(); // Both instants are the same moment on the timeline in UTC.
I want to add 5 seconds to current time
Date date = new Date();
date.setSeconds(date.getSeconds()+ 5);
System.out.println("old Value is: "+date);
System.out.println("New Value is: "+ date);
It generates the correct output exactly what I needed as:
Old Value is: Thu Apr 17 14:10:33 PKT 2014
New Value is: Thu Apr 17 14:10:38 PKT 2014
but it gives me a warning error message as
Multiple markers at this line
- The method getSeconds() from the type Date is deprecated
- The method setSeconds(int) from the type Date is
deprecated
What this means. Is it safe to ignore this warning? if not then how to handle it?
you can use date.setTime(date.getTime() + 5000)
You can try this. Calendar is the best solution you are looking at.
Date date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.parse("2014-04-17 14:53:25");
Calendar calendar=Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.SECOND,(calendar.get(Calendar.SECOND)-5));
System.out.println(calendar.getTime());
Out put:
Thu Apr 17 14:53:20 IST 2014
deprecated means that this method should't be used anymore because it can be removed from the Java language in favor of some other method (it probably won't be removed but it's not the preferable way of doing things anymore). Documentation suggests you to use Calendar.get(Calendar.SECOND) which is what you should use in your code.
Note that from Java 8 you can use LocalDateTime#getSecond method again.
Java 8 has completly different time-api and makes handling dates a lot easier. Here's an article
With Java Versions 5-7 (everything below should not be used IMHO) you should use Calendar (as Petr suggested)
If you are allowed to use third-party APIs, you should definitly take a look at JodaTime
showing deprecated warning that means
there is some better way available in java to do so.
java.time
The future visitors of this page are recommended to use java.time API. The date-time API of java.util 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.
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.
Just local time:
import java.time.LocalTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// ZoneId.systemDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to ZoneId.of("Europe/London")
LocalTime localTimeNow = LocalTime.now(ZoneId.systemDefault());
System.out.println(localTimeNow);
// After 5 seconds
LocalTime localTimeAfter5Sec = localTimeNow.plusSeconds(5);
System.out.println(localTimeAfter5Sec);
}
}
Local date & time:
import java.time.LocalDateTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// ZoneId.systemDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to ZoneId.of("Europe/London")
LocalDateTime ldtNow = LocalDateTime.now(ZoneId.systemDefault());
System.out.println(ldtNow);
// After 5 seconds
LocalDateTime ldtAfter5Sec = ldtNow.plusSeconds(5);
System.out.println(ldtAfter5Sec);
}
}
Date & time with timezone:
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
// ZoneId.systemDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to ZoneId.of("Europe/London")
ZonedDateTime zdtNow = ZonedDateTime.now(ZoneId.systemDefault());
System.out.println(zdtNow);
// After 5 seconds
ZonedDateTime zdtAfter5Sec = zdtNow.plusSeconds(5);
System.out.println(zdtAfter5Sec);
}
}
An instantaneous point on the time-line:
java.time.Instant models a single instantaneous point on the time-line and is independent of timezone. It's most commonly used functions, toEpochMilli and ofEpochMilli are used to convert an instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z, and milliseconds from the epoch of 1970-01-01T00:00:00Z to an instant respectively. Note that Z stands for Zulu and represents UTC+00:00.
import java.time.Instant;
public class Main {
public static void main(String[] args) {
// This moment
Instant now = Instant.now();
System.out.println(now);
// Moment after 5 sec
Instant momentAfter5Sec = now.plusSeconds(5);
System.out.println(momentAfter5Sec);
}
}
Learn more about the modern date-time API from Trail: Date Time.
Joda-time
An excerpt from the Home Page of Joda-Time
Joda-Time is the de facto standard date and time library for Java
prior to Java SE 8. Users are now asked to migrate to java.time
(JSR-310).
Just local time:
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;
public class Main {
public static void main(String[] args) {
// DateTimeZone.getDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to DateTimeZone.forID("Europe/London")
LocalTime localTimeNow = LocalTime.now(DateTimeZone.getDefault());
System.out.println(localTimeNow);
// After 5 seconds
LocalTime localTimeAfter5Sec = localTimeNow.plusSeconds(5);
System.out.println(localTimeAfter5Sec);
}
}
Local date & time:
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
// DateTimeZone.getDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to DateTimeZone.forID("Europe/London")
LocalDateTime ldtNow = LocalDateTime.now(DateTimeZone.getDefault());
System.out.println(ldtNow);
// After 5 seconds
LocalDateTime ldtAfter5Sec = ldtNow.plusSeconds(5);
System.out.println(ldtAfter5Sec);
}
}
Date & time with timezone:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public class Main {
public static void main(String[] args) {
// DateTimeZone.getDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to DateTimeZone.forID("Europe/London")
DateTime dtNow = new DateTime(DateTimeZone.getDefault());
System.out.println(dtNow);
// After 5 seconds
DateTime dtAfter5Sec = dtNow.plusSeconds(5);
System.out.println(dtAfter5Sec);
}
}
An instantaneous point on the time-line:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public class Main {
public static void main(String[] args) {
DateTime now = new DateTime(DateTimeZone.UTC);
System.out.println(now);
// After 5 seconds
DateTime after5Sec = now.plusSeconds(5);
System.out.println(after5Sec);
}
}
Legacy API:
The java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970. When you print an object of java.util.Date, its toString method returns the date-time calculated from this milliseconds value. Since java.util.Date does not have timezone information, it applies the timezone of your JVM and displays the same. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFomrat and obtain the formatted string from it.
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());
calendar.add(Calendar.SECOND, 5);// -5 if you want to subtract
System.out.println(calendar.getTime());
}
}
java.time.Instant as the bridge between the legacy and the modern API:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
Instant instant = date.toInstant();
// Now you can convert instant to other types of java.time e.g.
ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Dubai"));
System.out.println(zdt);
}
}
For whatsoever purpose, if you want to convert instant to an object of java.util.Date:
Date dateTime = Date.from(instant);
Easiest solution:
if it is the current date use:
Long seconds= 10; //update in seconds
//seconds*1000 to convert second to millisecond
Date dateAfterUpdation = new Date(System.currentTimeMillis() - (seconds*1000) );
For a specific Date:
Long seconds= 10; //update in seconds
//seconds*1000 to convert second to millisecond
Date dateAfterUpdation = new Date(oldDate.getTime() - (seconds*1000) );
Similarly, you can add or subtract any amount of time by this trick.
FYI, here is some example code using Joda-Time 2.3. The bundled java.util.Date and .Calendar classes are notoriously troublesome, and should be avoided.
Unlike a java.util.Date, a Joda-Time DateTime object has an assigned time zone.
When specifying time zones, use a proper time zone name. Avoid the three or four letter codes as they are neither standardized nor unique.
java.util.Date date = new java.util.Date(); // Has no time zone. Misnamed, as it contains both a date and a time portions.
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Karachi" );
DateTime dateTime = new DateTime( date, timeZone );
DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );
DateTime fiveSecondsAgo = dateTime.minusSeconds( 5 );
java.util.Date date2 = fiveSecondsAgo.toDate();
Dump to console…
System.out.println( "date: " + date );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "fiveSecondsAgo: " + fiveSecondsAgo );
System.out.println( "date2: " + date2 );
When run…
date: Thu Apr 17 14:44:01 PDT 2014
dateTime: 2014-04-18T02:44:01.773+05:00
dateTimeUtc: 2014-04-17T21:44:01.773Z
fiveSecondsAgo: 2014-04-18T02:43:56.773+05:00
date2: Thu Apr 17 14:43:56 PDT 2014
An easy way is to use apache DateUtils.
import org.apache.commons.lang.time.DateUtils;
DateUtils.addSeconds(now, 5); // Add 5 seconds.
DateUtils.addSeconds(now, -5); // Subtracting 5 seconds
You can also add/subtract minutes, hours, and so on...
I'm getting these times from Facebook events. E.g: start_time and it's a string like this:
2013-12-21T18:30:00+0100
Now I just want the time, like:
18.30
I tried to do it with this:
SimpleDateFormat formatter = new SimpleDateFormat(" EEEE, dd MMMM yyyy", java.util.Locale.getDefault());
Date formatted = null;
try {
formatted = formatter.parse(p.getStart_time());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String formattedString = formatted.toString();
txtStart_time.setText(""+formattedString);
p.getStart_time() is a String that gives me the date like I said before.
If I do this method, I get an error:
Unparseable date.
Does anybody know a work around?
You need two formats: one to parse the date and one to format it
String startTime = "2013-12-21T18:30:00+0100";
SimpleDateFormat incomingFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date = incomingFormat.parse(startTime);
SimpleDateFormat outgoingFormat = new SimpleDateFormat(" EEEE, dd MMMM yyyy", java.util.Locale.getDefault());
System.out.println(outgoingFormat.format(date));
prints
Saturday, 21 December 2013
I'm getting these times from Facebook events. E.g: start_time and it's
a string like this:
2013-12-21T18:30:00+0100
Now I just want the time, like:
18.30
Solution using java.time, the modern date-time API:
OffsetDateTime.parse(
"2013-12-21T18:30:00+0100",
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZ")
).toLocalTime()
Description: Your date-time string has a timezone offset of +01:00 hours. java.time API provides you with OffsetDateTime to contain the information of date-time units along with the timezone offset. Using the applicable DateTimeFormatter, parse the string into an OffsetDateTime and then get the LocalTime part of this date-time using OffsetDateTime#toLocalTime.
Demo using java.time API:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
System.out.println(OffsetDateTime.parse(
"2013-12-21T18:30:00+0100",
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZ")
).toLocalTime());
}
}
Output:
18:30
ONLINE DEMO
Note: You can use y instead of u here but I prefer u to y.
Learn more about the modern Date-Time API from Trail: Date Time.
A note about the legacy API:
The question and the accepted answer use java.util.Date and SimpleDateFormat which was the correct thing to do in 2013. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern date-time API. Since then, it is highly recommended to stop using the legacy date-time API.
Use something like yyyy-MM-dd'T'HH:mm:ssZ as parsing format instead of EEEE, dd MMMM yyyy.
Substring
If all you want is literally the time component lifted from that string, call the substring method on the String class…
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
String dateTimeStringFromFacebook = "2013-12-21T18:30:00+0100";
// Extract a substring.
String timeSubstring = dateTimeStringFromFacebook.substring( 11, 19 );
DateTime Object
If you want the time converted to a particular time zone, convert the string to a date-time object. Use a formatter to express just the time component.
Here is some example code using the Joda-Time 2.3 library. Avoid the notoriously bad java.util.Date/Calendar classes. Use either Joda-Time or the new java.time.* JSR 310 classes bundled with Java 8.
// From String to DateTime object.
DateTime dateTime = new DateTime( dateTimeStringFromFacebook, DateTimeZone.UTC );
// From DateTime object to String
// Extract just the hours, minutes, seconds.
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss");
String timeFragment_Paris = formatter.withZone( DateTimeZone.forID( "Europe/Paris" ) ).print( dateTime );
String timeFragment_Kolkata = formatter.withZone( DateTimeZone.forID( "Asia/Kolkata" ) ).print( dateTime ); // Formerly known as Calcutta, India.
Dump to console…
System.out.println( "dateTimeStringFromFacebook: " + dateTimeStringFromFacebook );
System.out.println( "timeSubstring: " + timeSubstring );
System.out.println( "dateTime: " + dateTime );
System.out.println( "timeFragment_Paris: " + timeFragment_Paris );
System.out.println( "timeFragment_Kolkata: " + timeFragment_Kolkata + " (Note the 00:30 difference due to +05:30 offset)");
When run…
dateTimeStringFromFacebook: 2013-12-21T18:30:00+0100
timeSubstring: 18:30:00
dateTime: 2013-12-21T17:30:00.000Z
timeFragment_Paris: 18:30:00
timeFragment_Kolkata: 23:00:00 (Note the 00:30 difference due to +05:30 offset)
Think Time Zone
Your question fails to address the question of time zone. Make a habit of always thinking about time zone whenever working with date-time values. If you mean the same time zone, say so explicitly. If you mean the default time zone of the Java environment, say so. If you mean UTC… well, you get the idea.