I having a hard time trying to format a string time into MM:DD::YY and only time. From an IP i getting the time in the following format
2021-09-10T00:37:42Z
and I'm want to display the date and time in:
09/08/2021
Time
09:50PM
Parse the given string into OffsetDateTime and then get LocalDate and LocalTime parts out of it.
import java.time.LocalDate;
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 = "2021-09-10T00:37:42Z";
OffsetDateTime odt = OffsetDateTime.parse(strDateTime);
LocalTime time = odt.toLocalTime();
LocalDate date = odt.toLocalDate();
System.out.println(time);
System.out.println(date);
// #########Custom formats #########
DateTimeFormatter dtfDate = DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH);
String formattedDateString = date.format(dtfDate);
System.out.println(formattedDateString);
DateTimeFormatter dtfTime = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
String formattedTimeString = time.format(dtfTime);
System.out.println(formattedTimeString);
}
}
Output:
00:37:42
2021-09-10
09/10/2021
12:37 AM
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
Update based on an important comment by Ole V.V.:
The OP — or their user — may want the date and time in their own time
zone.
In order to get the date and time parts in a specific timezone e.g. America/Los_Angeles, you should parse the given date-time string into ZonedDateTime and convert the same to the ZonedDateTime of the specific timezone using ZonedDateTime#withZoneSameInstant. Rest of the things will remain same as the original answer.
Demo:
import java.time.LocalDate;
import java.time.LocalTime;
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 strDateTime = "2021-09-10T00:37:42Z";
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime);
ZonedDateTime zdtLosAngeles = zdt.withZoneSameInstant(ZoneId.of("America/Los_Angeles"));
LocalTime time = zdtLosAngeles.toLocalTime();
LocalDate date = zdtLosAngeles.toLocalDate();
System.out.println(time);
System.out.println(date);
// #########Custom formats #########
DateTimeFormatter dtfDate = DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH);
String formattedDateString = date.format(dtfDate);
System.out.println(formattedDateString);
DateTimeFormatter dtfTime = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
String formattedTimeString = time.format(dtfTime);
System.out.println(formattedTimeString);
}
}
Output:
17:37:42
2021-09-09
09/09/2021
05:37 PM
ONLINE DEMO
* 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 an API for JSON parsing which requires a DateTimeFormatter instance in order to parse date time strings to OffsetDateTime. However I always get an exception Unable to obtain ZoneOffset from TemporalAccessor: {},ISO resolved to 2021-08-17T13:26:49 of type java.time.format.Parsed
The API uses OffsetDateTime.parse(String, DateFormatter).
// DateTimeFormatter instance to be provided to the API
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
// this is how the API uses the DateTimeFormatter instance
OffsetDateTime dateTime = OffsetDateTime.parse("20210817132649", formatter);
How do I have to create the DateTimeFormatter in order to deliver a ZoneOffset, so that the API is able to parse the DateTime correctly. The ZoneOffset may be UTC.
Update
I understood from you that you are using the API as follows:
apiClient.getJSON().setOffsetDateTimeFormat(DateTimeFormatter);
and you do not have a parameter to pass timezone information. In this case, you can use DateTimeFormatter#withZone as shown below:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss", Locale.ENGLISH)
.withZone(ZoneOffset.UTC);
OffsetDateTime odt = OffsetDateTime.parse("20210817132649", formatter);
System.out.println(odt);
}
}
Output:
2021-08-17T13:26:49Z
ONLINE DEMO
i.e. now, your call will be:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss", Locale.ENGLISH)
.withZone(ZoneOffset.UTC);
apiClient.getJSON().setOffsetDateTimeFormat(formatter);
Original answer
Your date-time string does not have a timezone offset. Parse it into a LocalDateTime and then apply the offset to it.
Demo:
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss", Locale.ENGLISH);
OffsetDateTime odt = LocalDateTime.parse("20210817132649", formatter)
.atOffset(ZoneOffset.UTC);
System.out.println(odt);
}
}
Output:
2021-08-17T13:26:49Z
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). You can specify a different timezone offset (e.g. ZoneOffset.of("+05:30")) as per your requirement.
In case you have ZoneId available
If you have ZoneId available, you should parse the given date-time string into a LocalDateTime and then apply the ZoneId to it to get a ZonedDateTime from which you can always obtain an OffsetDateTime. The best thing about a ZonedDateTime is that it has been designed to adjust the timezone offset automatically whereas an OffsetDateTime is used to represent a fixed timezone offset.
Demo:
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) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss", Locale.ENGLISH);
ZonedDateTime zdt = LocalDateTime.parse("20210817132649", formatter)
.atZone(ZoneId.of("Etc/UTC"));
OffsetDateTime odt = zdt.toOffsetDateTime();
System.out.println(odt);
}
}
Output:
2021-08-17T13:26:49Z
ONLINE DEMO
You can specify a different ZoneId(e.g. ZoneId.of("Asia/Kolkata")) as per your requirement.
Learn more about the modern Date-Time API* from Trail: Date Time.
* 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.
Well, the string you passed in does not contain zone information, while an OffsetDateTime requires zone information.
So you'll have to set a value for it.
You could use the DateTimeFormatterBuilder class, which then can be instructed to use some default value if a field is missing from the parsed information:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
.appendPattern("yyyyMMddHHmmss")
.toFormatter(Locale.ROOT);
You could also directly set an implied zone to the DateTimeFormatter:
DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneOffset.UTC);
Better use a ZonedDateTime - the difference being the Day Saving Time, and countries on with the same zone offset. Maybe using the default ZoneId.
private void showdataTable_btnActionPerformed(java.awt.event.ActionEvent evt) {
try {
DateFormat df = new SimpleDateFormat("YYYY-mm-dd'T'HH:MM:ss'Z'"); //set date format
String set = df.format(dateChoos1.getDate()); //add value to set
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("datetimes", set); //where date via set(date)
DBCursor cursor = table.find(whereQuery);
while (cursor.hasNext()) {
DBObject obj = cursor.next();
String ip_address = (String) obj.get("ip_address");
String mac_address = (String) obj.get("mac_address");
Date datetimes = (Date) obj.get("datetimes");
String url = (String) obj.get("url");
model.insertRow(model.getRowCount(), new Object[]{datetimes, ip_address, mac_address, url});
}
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
Your format, YYYY-mm-dd'T'HH:MM:ss'Z' is not correct. Let's discuss everything which is wrong with this format.
You have used Y instead of y: The symbol Y is used for Week year while y is used for Year. Check Difference between year-of-era and week-based-year? to learn more about it.
You have used mm for month: The correct symbol for the month is M.
You have used MM for minutes: The correct symbol for the minute is m.
You have enclosed Z within single quotes: The symbol, Z is used for Time zone whereas 'Z' is nothing but a character literal. Probably you want to format the timezone offset of +00:00 as Z and for this, you should in fact use X.
So, the correct format is as follows:
yyyy-MM-dd'T'HH:mm:ssX
A demo with the suggested format:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.ENGLISH);
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
System.out.println(sdf.format(date));
}
}
Output:
2021-01-14T08:13:01Z
Note that 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.
Use Date#toInstant to convert a java.util.Date object (the legacy type) to java.time.Instant (the modern type). Instant represents an instantaneous point on the time-line and should be just enough for most of your JSON operations. The Instant#toString returns the date-time string with UTC timezone offset which is compliant with ISO-8601 standards.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
Instant instant = date.toInstant();
// Print the value of instant#toString
System.out.println(instant);
OffsetDateTime odt = instant.atOffset(ZoneOffset.UTC);
System.out.println(odt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssX", Locale.ENGLISH);
System.out.println(dtf.format(odt));
}
}
Output:
2021-01-14T08:28:35.659Z
2021-01-14T08:28:35.659Z
2021-01-14T08:28:35Z
This question already has answers here:
Convert Json date to java date
(3 answers)
How can I convert Json Date to Java Date
(6 answers)
Closed 2 years ago.
so I have this problem converting Integer DateTime format to normal DateTime format in Java.
I have this this variable int DateTime, for example it is : "/Date(1484956800000)/" . And i am trying to convert it to normal date time and show it to the screen ...
I tried like this..
String dateAsText = new SimpleDateFormat("MM-dd HH:mm")
.format(new Date(Integer.parseInt(deals.getDate_time()) * 1000L));
// setting my textView with the string dateAsText
holder.Time.setText(dateAsText);
I suggest you stop using the outdated and error-prone java.util date-time API and SimpleDateFormat. Switch to the modern java.time date-time API and the corresponding formatting API (java.time.format). Learn more about the modern date-time API from Trail: Date Time.
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Obtain an instance of Instant using milliseconds from the epoch of
// 1970-01-01T00:00:00Z
Instant instant = Instant.ofEpochMilli(1484956800000L);
System.out.println(instant);
// Specify the time-zone
ZoneId myTimeZone = ZoneId.of("Europe/London");
// Obtain ZonedDateTime out of Instant
ZonedDateTime zdt = instant.atZone(myTimeZone);
// Obtain LocalDateTime out of ZonedDateTime
// Note that LocalDateTime throws away the important information of time-zone
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
// Custom format
String dateAsText = ldt.format(DateTimeFormatter.ofPattern("MM-dd HH:mm"));
System.out.println(dateAsText);
}
}
Output:
2017-01-21T00:00:00Z
2017-01-21T00:00
01-21 00:00
If you still want to use the poorly designed legacy java.util.Date, you can do it as follows:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date(1484956800000L);
System.out.println(date);
// Custom format
String dateAsText = new SimpleDateFormat("MM-dd HH:mm").format(date);
System.out.println(dateAsText);
}
}
Output:
Sat Jan 21 00:00:00 GMT 2017
01-21 00:00
I have a formatted date from sqllite database, to use this in a graph view I need to format it in a long number.
The format is:
2012-07-11 10:55:21
how can I convert it to milliseconds?
You can convert the string into a Date object using this code:-
Date d = DateFormat.parse(String s)
And then convert it into milliseconds by using the inbuilt method
long millisec = d.getTime();
Use date.getTime()
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd, HH:mm:ss");
formatter.setLenient(false);
String oldTime = "2012-07-11 10:55:21";
Date oldDate = formatter.parse(oldTime);
long oldMillis = oldDate.getTime();
try this:
import java.util.*;
public class ConvertDateIntoMilliSecondsExample{
public static void main(String args[]){
//create a Date object
Date date = new Date();
System.out.println("Date is : " + date);
//use getTime() method to retrieve milliseconds
System.out.println("Milliseconds since January 1, 1970, 00:00:00 GMT : "
+ date.getTime());
}
}
java.time
Solution using java.time, the modern date-time API*:
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) {
// Test
System.out.println(toMillis("2012-07-11 10:55:21"));
}
public static long toMillis(String strDateTime) {
// Replace the parameter, ZoneId.systemDefault() which returns JVM's default
// timezone, as applicable e.g. to ZoneId.of("America/New_York")
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH)
.withZone(ZoneId.systemDefault());
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
Instant instant = zdt.toInstant();
return instant.toEpochMilli();
}
}
Output:
1342000521000
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 will be giving input date time for a timezone and the timezone for the input date time and we want the relevant DateTime in the expected timezone.
And here is my method.
convertToTimezone("03/08/2010 20:19:00 PM","Asia/Shanghai","US/Central");
The above time is the time in Asia/Shanghai. We would like to know what is the corresponding time in US/Central.
It's working fine but I am getting a 1-hour difference from the actual time.
Can I know where I am going wrong?
Here is the code:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class DateUtil {
private static String format_date = "MM/dd/yyyy HH:mm:ss a";
public static void main(String a[]) {
try {
String sourceTimezone = "Asia/Shanghai";
String destTimezone = "US/Central";
String outputExpectedTimezone = convertToTimezone("03/08/2010 20:19:00 PM", sourceTimezone, destTimezone);
System.out.println("outputExpectedTimezone :" + outputExpectedTimezone);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static String convertToTimezone(String inputDate, String inputDateTimezone, String destinationDateTimezone)
throws Exception {
String outputDate = null;
SimpleDateFormat format = new SimpleDateFormat(format_date);
format.setTimeZone(TimeZone.getTimeZone(inputDateTimezone));
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(inputDateTimezone));
calendar.setTime(format.parse(inputDate));
calendar.add(Calendar.MILLISECOND, -(calendar.getTimeZone().getRawOffset()));
calendar.add(Calendar.MILLISECOND, -calendar.getTimeZone().getDSTSavings());
calendar.add(Calendar.MILLISECOND, TimeZone.getTimeZone(destinationDateTimezone).getRawOffset());
outputDate = format.format(calendar.getTime());
return outputDate;
}
}
You shouldn't be adding anything to the calendar - that represents a specific instant in time. In fact, you don't need a calendar at all.
Instead, have two different formats, one for each time zone:
public static String convertToTimezone(String inputDate,
String inputDateTimezone,
String destinationDateTimezone)
throws Exception
{
SimpleDateFormat parser = new SimpleDateFormat(format_date);
parser.setTimeZone(TimeZone.getTimeZone(inputDateTimezone));
Date date = parser.parse(inputDate);
SimpleDateFormat formatter = new SimpleDateFormat(format_date);
formatter.setTimeZone(TimeZone.getTimeZone(outputDateTimezone));
return formatter.format(date);
}
As an aside, I'd thoroughly recommend using Joda Time instead of the built-in date/time API.
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:
Since your input Date-Time does not have timezone information, parse it into a LocalDateTime
Attach the timezone of the input Date-Time with it to get a ZonedDateTime
Use the ZonedDateTime#withZoneSameInstant to convert this ZonedDateTime to the target ZonedDateTime
Return the formatted target ZonedDateTime.
Demo:
import java.time.LocalDateTime;
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) {
// Tests
System.out.println(convertToTimezone("03/08/2010 20:19:00 PM", "Asia/Shanghai", "US/Central"));
System.out.println(convertToTimezone("03/08/2010 20:19:00 PM", "Asia/Shanghai", "America/Mexico_City"));
}
static String convertToTimezone(String inputDate, String inputDateTimezone, String destinationDateTimezone) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss a", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(inputDate, dtf);
ZonedDateTime zdtInput = ldt.atZone(ZoneId.of(inputDateTimezone));
ZonedDateTime zdtDestination = zdtInput.withZoneSameInstant(ZoneId.of(destinationDateTimezone));
return zdtDestination.format(dtf);
}
}
Output:
03/08/2010 06:19:00 AM
03/08/2010 06:19:00 AM
ONLINE DEMO
Note: Avoid using the deprecated ID, US/Central. Use the standard ID, America/Mexico_City where Mexico City is the largest city in this timezone.
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.