I need to convert a 24 hour date format for a given string into milliseconds. But I get the same milliseconds for 00:10:00 and 12:10:00. This is my code sample; please assist me.
DateFormat formate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
formate.parse("2013-10-31 12:10:00").getTime(); // return 1383158400000
formate.parse("2013-10-31 00:10:00").getTime(); // return 1383158400000
I am using 24 hours format, but I get the same result for 2 different times. Where is the mistake? Please help me to find out the problem.
You are using the 12-hour hh format; use the 24-hour HH (capitalized) format.
DateFormat formate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat date symbols
H Hour in day (0-23) Number 0
h Hour in am/pm (1-12) Number 12
java.time
Without AM/PM marker, the date-time parser considers the hour in 24-Hour format for which the symbol is H instead of h.
Changing that will fix your problem but the legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using them completely and switch to java.time, the modern date-time API*.
Demo using modern date-time API:
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH).withZone(ZoneOffset.UTC);
System.out.println(Instant.from(dtf.parse("2013-10-31 12:10:00")).toEpochMilli());
System.out.println(Instant.from(dtf.parse("2013-10-31 00:10:00")).toEpochMilli());
}
}
Output:
1383221400000
1383178200000
Learn more about the 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
I have to call a web service which is expecting a Date field but they want it in the following format YYYY-MM-DDThh:mm:ss.sssZ. How can I do this?
I tried the following
OffsetDateTime transactionTime = OffsetDateTime.now(ZoneOffset.UTC);
Date.from(transactionTime.toInstant());
but this didn't work. transactionTime is 2021-06-01T15:11:09.942843400Z, but Date.from converts it to Tue Jun 01 11:11:09 EDT 2021.
BTW, I'm using Java 11
Instant.now().toString()
See that code run live at IdeOne.com.
2021-06-01T15:21:16.783779Z
That format is defined in the ISO 8601 standard. The Z on end means an offset-from-UTC of zero hours-minutes-seconds. Pronounced “Zulu”.
Use java.time.Instant to represent a moment as seen in UTC.
Going the other direction, from text to object.
Instant.parse( "2021-06-01T15:21:16.783779Z" )
If you want only milliseconds, you can lop off any microseconds and nanoseconds by truncating.
Instant.now().truncatedTo( ChronoUnit.MILLIS ) ;
Never use the legacy Date class. Use only the java.time classes.
Use DateTimeFormatter to format the Date-Time object
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
OffsetDateTime transactionTime = OffsetDateTime.now(ZoneOffset.UTC);
String formatted = transactionTime.format(dtf);
System.out.println(formatted);
}
}
Output:
2021-06-01T15:49:45.198Z
Learn more about the modern Date-Time API from Trail: Date Time.
What if I want to use java.util.Date?
For any reason, if you need to convert this object of OffsetDateTime to an object of java.util.Date, you can do so as follows:
Date date = Date.from(transactionTime.toInstant());
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 Date does not have timezone information, it applies the JVM's timezone to return the value of Date#toString in the format, EEE MMM dd HH:mm:ss z yyyy calculated 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 timezone set to the applicable one e.g.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String strDate = sdf.format(date);
System.out.println(strDate);
Output:
2021-06-01T15:49:45.198Z
Some other important notes:
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*.
Most of the symbols that you have used in YYYY-MM-DDThh:mm:ss.sssZ are wrong. Check the description of the symbols from the documentation pages of DateTimeFormatter and SimpleDateFormat.
* 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 am getting the time object in the form of a string from a rest service . I need to extract the time and then do some time operation.The given time string is "2015-06-16T14:58:48Z". I tried the below code , to convert the string to the time , however , getting incorrect values.
String time = "2015-06-16T14:58:48Z";
SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-DD'T'hh:mm:ss'Z'", Locale.US);
String dateInString = "2015-06-16T14:58:48Z";
Date date = formatter.parse(dateInString);
System.out.println("Original String : " + time);
System.out.println("After converting to time : " + formatter.format(date));
The output that i am getting is as below:
Original String : 2015-06-16T14:58:48Z
After converting to time : 2015-12-362T02:58:48Z
The converted date somehow is getting wrong value.Please suggest where is the mistake.Thanks.
You format string has a couple of mistakes:
Y means the week year, not the year, which is y
D means the day of the year. You should have used d, which means the day of the month.
h means a 12-hour notation time of day. Since you have 14 you should use H, which handle a 24-hour notation.
To sum it all up:
SimpleDateFormat formatter =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.US);
change SimpleDateFormat to this..
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ssX", Locale.US);
java.time
The root cause of the problem is using wrong symbols
Y (which specifies week-based-year) instead of y (which specifies year-of-era)
D (which specifies day-of-year) instead of d (which specifies day-of-month).
h (which specifies clock-hour-of-am-pm) instead of H (which specifies hour-of-day).
Check the documentation page
to learn more about these symbols.
Also, note that the legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
Solution using the modern API:
The modern date-time API is based on ISO 8601 and does not require you to use a DateTimeFormatter object explicitly as long as the date-time string conforms to the ISO 8601 standards. Your date-time string conforms to ISO 8601 standards (or the default format used by OffsetDateTime#parse).
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "2015-06-16T14:58:48Z";
OffsetDateTime odt = OffsetDateTime.parse(strDateTime);
System.out.println(odt);
// ########################Extract time information########################
LocalTime time = odt.toLocalTime();
// You can also get it as time.getHour()
// Extract other units in a similar way
int hour = odt.getHour();
// Also using time.format(DateTimeFormatter.ofPattern("a", Locale.ENGLISH));
String amPm = odt.format(DateTimeFormatter.ofPattern("h a", Locale.ENGLISH));
System.out.println(time);
System.out.println(hour);
System.out.println(amPm);
}
}
Output:
2015-06-16T14:58:48Z
14:58:48
14
2 PM
Note:
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).
For any reason, if you need to convert this object of OffsetDateTime to an object of java.util.Date, you can do so as follows:
Date date = Date.from(odt.toInstant());
Learn more about the 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.
Please check the below code. I am trying to get the difference but every time getting 0.
Can anybody please point me what is the problem with below code?
SimpleDateFormat sDateFormat = new SimpleDateFormat("hh:mm:ss dd/mm/yyyy");
try {
long d1 = sDateFormat.parse("10:04:00 04/04/2014").getTime();
long d2 = sDateFormat.parse("10:09:00 04/04/2014").getTime();
long difference = d2 - d1;
Log.i(TAG,">> Difference = "+difference);
} catch (ParseException e) {
e.printStackTrace();
}
your formatter does not fit the date format used.
Try:
new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
From Android Developer documentation of SimpleDateFormat, you can see M is for Month and m is for minute...
M month in year (Text) M:1 MM:01 MMM:Jan MMMM:January MMMMM:J
m minute in hour (Number) 30
So, you should change the date format from this...
hh:mm:ss dd/mm/yyyy
to this...
hh:mm:ss dd/MM/yyyy
I hope this format correction will solve your problem.
Your format, hh:mm:ss dd/mm/yyyy has two problems:
h is used for 12-Hour time format i.e. a time format with AM/PM marker which is not the case with your date-time strings. You need to use H which is used for a 24-Hour time format.
m is not used for a month. For a month, you need to use M.
Apart from this, the legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time, the modern date-time API*.
Demo using modern date-time API:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String args[]) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:m:s d/M/u");
LocalDateTime start = LocalDateTime.parse("10:04:00 04/04/2014", dtf);
LocalDateTime end = LocalDateTime.parse("10:09:00 04/04/2014", dtf);
long diff = ChronoUnit.MILLIS.between(start, end);
System.out.println(diff);
}
}
Output:
300000
Learn more about the 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 need to convert epoch timestamp to date and time.
I have used the following code to convert but it converts to a wrong date, year and time.
String date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
.format(new java.util.Date (1319286637/1000));
Expected output was today’s date at some time, but the result I got was:
01/01/1970 05:51:59
The Date(long) constructor takes milliseconds. You should be multiplying by 1000, not dividing the epoch time you have.
In brief:
Instant.ofEpochSecond( 1_319_286_637L )
2011-10-22T12:30:37Z
Solution using java.time, the modern API:
import java.time.Instant;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.ofEpochSecond(1319286637L);
System.out.println(instant);
}
}
Output:
2011-10-22T12:30:37Z
An Instant represents an instantaneous point on the timeline. 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).
You can convert an Instant to other Date-Time types 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 instant = Instant.ofEpochSecond(1319286637);
ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Kolkata"));
System.out.println(zdt);
// A custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss", Locale.ENGLISH);
System.out.println(dtf.format(zdt));
}
}
Output:
2011-10-22T18:00:37+05:30[Asia/Kolkata]
10/22/2011 18:00:37
Learn more about java.time, the modern Date-Time API* from Trail: Date Time.
Note: 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*. However, for any purpose, 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);
* 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.
We're searching for information on how to format instances of java.util.Calendar and more general information and coding hints regarding transition from using java.util.Date to java.util.Calendar.
best,
phil
My hint would be not to use either Date or Calendar. Use Joda Time instead. It's much, much nicer than the built-in classes. JSR-310 will hopefully, eventually bring something Joda-like into the main library, but for the moment Joda is your best bet.
If you must stick to Date/Calendar, see java.text.DateFormat and java.text.SimpleDateFormat. Remember that they're not thread-safe though :(
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:
If you are getting an object of java.util.Date from some API, your first step should be to convert it into Instant using Date#toInstant which can be converted to other types of modern Date-Time API.
A demo with the modern Date-Time API:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.now();
System.out.println(instant);
ZonedDateTime zdtUtc = instant.atZone(ZoneId.of("Etc/UTC"));
System.out.println(zdtUtc);
ZonedDateTime zdtNewYork = instant.atZone(ZoneId.of("America/New_York"));
System.out.println(zdtNewYork);
// Fixed offset
OffsetDateTime odtUtc = instant.atOffset(ZoneOffset.UTC);
System.out.println(odtUtc);
OffsetDateTime odtWithOffset0530Hours = instant.atOffset(ZoneOffset.of("+05:30"));
System.out.println(odtWithOffset0530Hours);
// OffsetDateTime from ZonedDateTime
OffsetDateTime odtNewYork = zdtNewYork.toOffsetDateTime();
System.out.println(odtNewYork);
// LocalDate in New York
LocalDate todayNewYork = zdtNewYork.toLocalDate();
System.out.println(todayNewYork);
// Alternatively
System.out.println(LocalDate.now(ZoneId.of("America/New_York")));
// LocalDateTime in New York
LocalDateTime nowNewYork = zdtNewYork.toLocalDateTime();
System.out.println(nowNewYork);
// Alternatively
System.out.println(LocalDateTime.now(ZoneId.of("America/New_York")));
// Formatted output
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMMM dd HH:mm:ss z uuuu", Locale.ENGLISH);
System.out.println(dtf.format(zdtNewYork));
}
}
Output:
2021-07-14T19:22:13.544911Z
2021-07-14T19:22:13.544911Z[Etc/UTC]
2021-07-14T15:22:13.544911-04:00[America/New_York]
2021-07-14T19:22:13.544911Z
2021-07-15T00:52:13.544911+05:30
2021-07-14T15:22:13.544911-04:00
2021-07-14
2021-07-14
2021-07-14T15:22:13.544911
2021-07-14T15:22:13.586971
Wed July 14 15:22:13 EDT 2021
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
Some helpful answers using java.time API:
Check this answer and this answer to learn how to use java.time API with JDBC.
How to use ParsePostion?
Timezone conversion.
SimpleDateFormat does not handle fraction-of-second beyond three digits in the millisecond part correctly.
How to convert LocalDate to ZonedDateTime?
'Z' is not the same as Z.
Day-of-month with ordinal.
The standard library does not support a formatted Date-Time object.
Never use SimpleDateFormat or DateTimeFormatter without a Locale.
How to check if timestamp (epoch time) is of today's or yesterday's?
* 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.