I've got a Calendar Date in Java.
I need to convert it in a String with this format :
2020-12-29T00:00:00+01:00
How can I do it?
Thank you so much for your help.
Get the Date object by calling Calendar#getTime and format it using a SimpleDateFormat with the format, yyyy-MM-dd'T'HH:mm:ssXXX.
Note: Since the desired string has timezone offset of +01:00 hours, make sure you set the timezone of the SimpleDateFormat object to TimeZone.getTimeZone("GMT+1") before calling SimpleDateFormat#format.
Demo:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws ParseException {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+1"));
Date date = calendar.getTime();
String formatted = sdf.format(date);
System.out.println(formatted);
}
}
Another example:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws ParseException {
String dateTimeString = "2020-12-29T00:00:00+01:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date obj = sdf.parse(dateTimeString);
Calendar calendar = Calendar.getInstance();
calendar.setTime(obj);
// Formatting this calendar object
Date date = calendar.getTime();
sdf.setTimeZone(TimeZone.getTimeZone("GMT+1"));
String formatted = sdf.format(date);
System.out.println(formatted);
}
}
Output:
2020-12-29T00:00:00+01:00
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work.
Here’s a formatter for your desired format:
private static final DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX");
With this we may do:
ZoneId zone = ZoneId.of("Asia/Barnaul");
ZonedDateTime dateTime
= LocalDate.of(2020, Month.DECEMBER, 29).atStartOfDay(zone);
String formatted = dateTime.format(formatter);
System.out.println(formatted);
Output from this example snipoet is:
2020-12-29T00:00:00+07:00
If you cannot avoid getting a Calendar
If you are getting a Calendar object from a legacy API that you cannot afford to upgrade to java.time just now, convert it to ZonedDateTime. It is almost certainly really a GregorianCalendar (or formatting into that format would not make much sense), which makes the conversion straightforward.
Calendar yourCalendar = getCalendarFromLegacyApi();
ZonedDateTime dateTime
= ((GregorianCalendar) yourCalendar).toZonedDateTime();
The rest is as before, as is the output.
If you need to take into account the possibility that the Calendar is not a GregorianCalendar, use this slightly more complicated conversion instead:
ZonedDateTime dateTime = yourCalendar.toInstant()
.atZone(yourCalendar.getTimeZone().toZoneId());
Link
Oracle tutorial: Date Time explaining how to use java.time.
Related
I tried reading a lot about the date formatting with time zone, but it doesn't make sense to me.
My DB shows this datetime: 2022-12-01 04:00:00.000 +08:00
My UI shows it as: Thu 01/12/2022 12:00
I need to compare between them to verify they are the same. I tried to convert the DB time like this:
String dbDate = "2022-12-01 04:00:00.000 +08:00";
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS XXX");
Date date = sf.parse(dbDate)
sf = new SimpleDateFormat("EEE dd/MM/yyy HH:mm");
String uiDate = sf.format(date);
The results received is a completely different date: 'Wed 30/11/2022 22:02'.
I don't understand the logic here and would appreciate help in converting it correctly.
As already commented by Yonatan Karp-Rudin, you can not compare a date-time with time-zone offset with another without time-zone offset. A clear way to compare the two date-times is to bring them to a single time-zone e.g. you can apply the same time-zone offset to the UI date-time as of the DB date-time.
In March 2014, java.time API supplanted the error-prone legacy date-time API. Since then, it has been strongly recommended to use this modern date-time API.
Demo using java.time API:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String dt1 = "2022-12-01 04:00:00.000 +08:00";
String dt2 = "Thu 01/12/2022 12:00";
DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS XXX", Locale.ENGLISH);
OffsetDateTime odt1 = OffsetDateTime.parse(dt1, dtf1);
System.out.println(odt1);
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("EEE dd/MM/uuuu HH:mm", Locale.ENGLISH)
.withZone(odt1.getOffset());
OffsetDateTime odt2 = OffsetDateTime.parse(dt2, dtf2);
System.out.println(odt2);
System.out.println(odt1.equals(odt2));
}
}
Output:
2022-12-01T04:00+08:00
2022-12-01T12:00+08:00
false
Assuming both the date-times belong to the same time-zone offset, another way to compare them would be compare them without time-zone i.e. comparing their date-time part only (LocalDateTime).
Demo:
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String dt1 = "2022-12-01 04:00:00.000 +08:00";
String dt2 = "Thu 01/12/2022 12:00";
DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS XXX", Locale.ENGLISH);
LocalDateTime ldt1 = OffsetDateTime.parse(dt1, dtf1).toLocalDateTime();
System.out.println(ldt1);
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("EEE dd/MM/uuuu HH:mm", Locale.ENGLISH);
LocalDateTime ldt2 = LocalDateTime.parse(dt2, dtf2);
System.out.println(ldt2);
System.out.println(ldt1.equals(ldt2));
}
}
Output:
2022-12-01T04:00
2022-12-01T12:00
false
The modern date-time API (java.time API) provides you with tools to do the same thing in many ways e.g. in the 1st demo, we could obtain the OffsetDateTime for your UI date-time string by parsing it into a LocalDateTime as shown in the 2nd demo and then using one of the ways shown in this answer where ZoneOffset offset = odt1.getOffset().
By the way, here is an example of how you format a date-time with time-zone offset to another format:
public class Main {
public static void main(String[] args) {
String dtDb = "2022-12-01 04:00:00.000 +08:00";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS XXX", Locale.ENGLISH);
OffsetDateTime odtDb = OffsetDateTime.parse(dtDb, parser);
System.out.println(odtDb);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE dd/MM/uuuu HH:mm", Locale.ENGLISH);
String strDtUi = odtDb.format(formatter);
System.out.println(strDtUi);
}
}
Output:
2022-12-01T04:00+08:00
Thu 01/12/2022 04:00
Learn more about the modern Date-Time API from Trail: Date Time.
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
Not able to parse the following date. Getting parse exception. Please help in finding error :
String myDate = "2020–03–01 3:15 pm";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm aa",Locale.ENGLISH);
Date date = sdf.parse(myDate);
The separator character that you have used to separate the year, the month and the day doesn't seem to be correct. I suggest you type the date-time string again instead of copying and pasting it from somewhere. I also recommend you switch from the outdated date-time API to the modern one.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String myDate = "2020-03-01 3:15 pm";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("u-M-d h:m a")
.toFormatter(Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(myDate, formatter);
System.out.println(ldt);
}
}
Output:
2020-03-01T15:15
If you still want to use the legacy date-time API, you can do it as follows:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
String myDate = "2020-03-01 3:15 pm";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd h:mm aa", Locale.ENGLISH);
Date date = sdf.parse(myDate);
System.out.println(date);
}
}
Output:
Sun Mar 01 15:15:00 GMT 2020
Note that I've used a single h to match your date-time string.
From the looks of it your date string contains – (dash) instead of - (hyphen).
Try using hyphens in the date instead and see if it manages to parse it correctly.
Bonus ascii table details:
Dash (-):
.
Hyphen (-):
Is there any way in java(java.util.* or Joda api ) to convert "2020-04-03 20:17:46" to "yyyy-MM-dd'T'HH:mm:ss"
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.parse("2020-04-03 20:17:46")
its giving java.text.parseException always
Just for the case you are using Java 8 or above, make use of java.time.
See this simple example:
public static void main(String[] args) {
// example datetime
String datetime = "2020-04-03 20:17:46";
// create a formatter that parses datetimes of this pattern
DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// then parse the datetime with that formatter
LocalDateTime ldt = LocalDateTime.parse(datetime, parserDtf);
// in order to output the parsed datetime, use the default formatter (implicitly)
System.out.println(ldt);
// or format it in a totally different way
System.out.println(ldt.format(
DateTimeFormatter.ofPattern("EEE, dd. 'of' MMM 'at' hh-mm-ss a",
Locale.ENGLISH)
)
);
}
This outputs
2020-04-03T20:17:46
Fri, 03. of Apr at 08-17-46 PM
Please note that this doesn't consider any time zone or offset, it just represents a date and time consisting of the passed or parsed years, months, days, hours, minutes and seconds, nothing else.
Do not use Date/Time API from java.util.* as most of them are now outdated. Use java.time API instead.
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) throws IOException {
String strDatetime = "2020-04-03 20:17:46";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parsedDate = LocalDateTime.parse(strDatetime, formatter);
System.out.println(parsedDate);
}
}
Output:
2020-04-03T20:17:46
Learn more about DateTimeFormatter at https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
Could this help you? http://tutorials.jenkov.com/java-internationalization/simpledateformat.html
First you need to parse the String with the old format, you will get a Date object. Then Create a new SimpleDateFormat with your new format, then you can format the Date object.
String dateString = "2020-04-03 20:17:46";
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(dateString);
String formattedDate = output.format(date);
It do not work that way directly but if you still want to do it then, here is the process.
Create an object of SimpleDateFormat with pattern "yyyy-MM-dd HH:mm:ss")
use this to parse the string. Ultimately you are going to get date in both cases. Is there any specific reason for using T in pattern for dates which do not contain them?
Use LocalDateTime.
Timestamp timestamp = Timestamp.parse("2020-04-03 20:17:46");
LocalDateTime localDateTime = timestamp.toLocalDateTime();
System.out.println(localDateTime); // 2020-04-03T20:17:46
I am currently working on converting from date to string. After that I convert that string to datetime. But it error. Anyone can help me?
Here is the code.
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.DateTimeFormatter
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
SimpleDateFormat outFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String dt1 = outFormat.format(date1);
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime dt = formatter.parseDateTime(dt1);
You're doing entirely too much work. Joda Time can convert for you in its parse(String, DateTimeFormatter) method.
DateTime dateTime = DateTime.parse(dt1, formatter);
Alternatively, if your string were in ISO8601 format (that is, yyyy-MM-dd'T'HH:mm:ssZ), you could just use parse(String) instead:
DateTime dateTime = DateTime.parse(dt1);