I am trying to parse a String into a Calendar but right now I'm having problems at TimeZone:
My code:
public static Calendar convertStringToFullDates(String dateString) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(PATTENT_FULL_DATE_FORMAT, Locale.US);
try {
cal.setTime(sdf.parse(dateString));
} catch (ParseException e) {
DebugLog.e(e.getLocalizedMessage());
}
return cal;
}
and String :
String str = "Fri May 11 00:00:00 ICT 2018";
and pattern:
private static final String PATTENT_FULL_DATE_FORMAT = "EEE MMM dd HH:mm:ss z yyyy";
I tried but it throws an exception like this:
Unparseable date: "Fri May 11 00:00:00 ICT 2018"
How to solve this problem?
The following code works for me:
public class Main {
public static void main(String[] args) throws ParseException {
String str = "Fri May 11 00:00:00 ICT 2018";
final String PATTENT_FULL_DATE_FORMAT = "EEE MMM dd HH:mm:ss z yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(PATTENT_FULL_DATE_FORMAT, Locale.US);
Date date = sdf.parse(str);
System.out.println(date);
}
}
Note that java.util date-time classes are outdated and error-prone and so is their formatting API, SimpleDateFormat. I suggest you should stop using them completely and switch to the modern date-time API.
If you are doing it for your 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.
Using the modern date-time API:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String str = "Fri May 11 00:00:00 ICT 2018";
final String PATTENT_FULL_DATE_FORMAT = "EEE MMM dd HH:mm:ss z yyyy";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(PATTENT_FULL_DATE_FORMAT, Locale.US);
ZonedDateTime zdt = ZonedDateTime.parse(str, dtf);
System.out.println(zdt);
// Print the date-time in a custom format
System.out.println(zdt.format(dtf));
}
}
Output:
2018-05-11T00:00+07:00[Asia/Bangkok]
Fri May 11 00:00:00 ICT 2018
Learn more about the modern date-time API at Trail: Date Time.
Related
Hi I am trying to convert a String into date using DateTimeFormatter,
such as "20210628" to "Mon Jun 28 00:00:00 UTC 2021".
It can be achieved easily using SimpleDateFormatter but I want to achieve it using DateTimeFormatter.
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.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("uuuuMMdd", Locale.ENGLISH);
LocalDate date = LocalDate.parse("20210628", dtfInput);
OffsetDateTime odt = date.atTime(OffsetTime.of(LocalTime.MIN, ZoneOffset.UTC));
System.out.println(odt);
// Custom format
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss O uuuu", Locale.ENGLISH);
System.out.println(dtfOutput.format(odt));
}
}
Output:
2021-06-28T00:00Z
Mon Jun 28 00:00:00 GMT 2021
ONLINE DEMO
Alternatively,
import java.time.LocalDate;
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 dtfInput = DateTimeFormatter.ofPattern("uuuuMMdd", Locale.ENGLISH);
LocalDate date = LocalDate.parse("20210628", dtfInput);
ZonedDateTime zdt = date.atStartOfDay(ZoneId.of("Etc/UTC"));
System.out.println(zdt);
// Custom format
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss O uuuu", Locale.ENGLISH);
System.out.println(dtfOutput.format(zdt));
}
}
Output:
2021-06-28T00:00Z[Etc/UTC]
Mon Jun 28 00:00:00 GMT 2021
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
A different approach using java.time, too...
Use a DateTimeFormatterBuilder to get full control over String conversion.
Here's a small example that really prints UTC instead of GMT or Z in the desired output:
public static void main(String[] args) {
// example String
String value = "20210628";
// define a formatter that parses the example String
DateTimeFormatter dateParser = DateTimeFormatter.ofPattern("uuuuMMdd");
// define a formatter that converts to a String as desired
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendPattern("EEE MMM dd HH:mm:ss")
.appendLiteral(' ')
.appendZoneRegionId()
.appendLiteral(' ')
.appendPattern("uuuu")
.toFormatter(Locale.ENGLISH);
// parse the date and use the formatter in order to get the desired result
String otherValue = LocalDate.parse(value, dateParser)
// add the start of the day
.atStartOfDay()
// apply the desired zone
.atZone(ZoneId.of("UTC"))
// and format it
.format(dtf);
// finally print the conversion
System.out.println(value + " ---> " + otherValue);
}
The output will be as follows:
20210628 ---> Mon Jun 28 00:00:00 UTC 2021
If you already have a LocalDateTime object then you can use the following.
String getFormattedDate(LocalDateTime datetime){
DateTimeFormatter formatterPreUTC = DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss");
DateTimeFormatter formatterPostUTC = DateTimeFormatter.ofPattern("YYYY");
String textPreUTCPart = datetime.format(formatterPreUTC);
String utc = " UTC ";
String textPostUTCPart = datetime.format(formatterPostUTC);
return textPreUTCPart + utc + textPostUTCPart;
}
In this code,
String str="Sun Feb 07 00:27:16 CET 2021";
SimpleDateFormat sdf=new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
try {
java.util.Date date=sdf.parse(str);
System.out.print(date.getTime());
} catch (ParseException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
It shows
GRAVE: null
java.text.ParseException: Unparseable date: "Sun Feb 07 00:27:16 CET 2021"
How to solve it plz!
There are two problems with your code:
Not using the correct format: you have used E instead of EEE
Not using Locale: make it a habit to use the applicable Locale with date-time parsing/formatting API. Your date-time string is in English and therefore you should use an English-specific locale e.g. Locale.ENGLISH, Locale.US etc.
Correct code:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
String str = "Sun Feb 07 00:27:16 CET 2021";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
java.util.Date date = sdf.parse(str);
System.out.print(date.getTime());
}
}
Output:
1612654036000
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.
Using the modern date-time API:
import java.text.ParseException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
String str = "Sun Feb 07 00:27:16 CET 2021";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z uuuu", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(str, dtf);
System.out.println(zdt);
System.out.println(zdt.toInstant().toEpochMilli());
}
}
Output:
2021-02-07T00:27:16+01:00[Europe/Paris]
1612654036000
Learn more about the modern date-time API from Trail: Date Time.
String sDate = "06.08.2020" // 06 day 08 month 2020 is year
This is the date i have in my txt file. I use them in JTable. To sort the table i convert them to date with this DateFormatter.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
And it does convert the string to date as this.
LocalDate date = LocalDate.parse(sDate,formatter);
//The date : Thu Aug 06 00:00:00 TRT 2020
Now i need to convert it like the first date 06.08.2020.
But i can't use date as input. Because i get it from JTable so i get it as String.
So i tryed this code.
String sDate1 = "Thu Aug 06 00:00:00 TRT 2020";// The date i get from JTable
LocalDate lastdate = LocalDate.parse(sDate1,formatter);
sDate1 = formatter.format(lastdate);
But i get an error as this Text 'Thu Aug 06 00:00:00 TRT 2020' could not be parsed at index 0.
So this cone not works fine : LocalDate lastdate = LocalDate.parse(sDate1,formatter);
I cant see where is the problem.
I cannot reproduce the behaviour you describe. The following code worked fine for me:
import java.util.*;
import java.text.*;
public class MyClass {
public static void main(String args[]) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String date = "06.08.2020";
Date date1 = sdf.parse(date);
String result = sdf.format(date1);
System.out.println("Date = " + result);
}
}
Output: Date = 06.08.2020
That being said, if at all possible you should switch to the new java.time.* API.
Where your code failed:
SimpleDateFormat sdf1=new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
String dateStr = "06.08.2020";
sdf1.parse(dateStr);
As you can see, the pattern of the SimpleDateFormat and that of the date string do not match and therefore, this code will throw ParseException.
How to make it work?
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);
You must have already got why it worked. It worked because the pattern of the SimpleDateFormat matches with that of the dateStr string.
Can I format the Date object (i.e. date) into the original string?
Yes, just use the same format which you used to parse the original string as shown below:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);
// Display in the default format
System.out.println(date);
// Format into the string
dateStr = sdf.format(date);
System.out.println(dateStr);
A piece of advice:
I recommend you switch from the outdated and error-prone java.util date-time API and SimpleDateFormat to the modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time.
Using the modern date-time API:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
String dateStr = "06.08.2020";
LocalDate date = LocalDate.parse(dateStr, formatter);
// Display in the default format
System.out.println(date);
// Format into the string
dateStr = formatter.format(date);
System.out.println(dateStr);
I don't see any difference using the legacy API and the modern API:
That's true for this simple example but when you will need to do complex operations using date and time, you will find the modern date-time API smart and clean while the legacy API complex and error-prone.
Demo:
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Given date-time string
String strDate = "Thu Aug 06 00:00:00 TRT 2020";
// Replace TRT with standard time-zone string
strDate = strDate.replace("TRT", "Europe/Istanbul");
// Define formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzzz yyyy");
// Parse the date-time string into ZonedDateTime
ZonedDateTime zdt = ZonedDateTime.parse(strDate, formatter);
System.out.println(zdt);
// If you wish, convert ZonedDateTime into LocalDateTime
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2020-08-06T00:00+03:00[Europe/Istanbul]
2020-08-06T00:00
I want to parse a date in this format: "Wed Aug 26 2020 11:26:46 GMT+0200" into a date. But I don't know how to do it. I tried this:
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = parser.parse(split[0]); //error line
String formattedDate = formatter.format(date);
I am getting this error: Unparseable date: "Wed Aug 26 2020 11:26:46 GMT+0200". Is my date format wrong? And if so could somebody please point me in the right direction?
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.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Given date-time string
String dateTimeStr = "Wed Aug 26 2020 11:26:46 GMT+0200";
// Parse the given date-time string to OffsetDateTime
OffsetDateTime odt = OffsetDateTime.parse(dateTimeStr,
DateTimeFormatter.ofPattern("E MMM d u H:m:s zX", Locale.ENGLISH));
// Display OffsetDateTime
System.out.println(odt);
}
}
Output:
2020-08-26T11:26:46+02:00
Using the legacy API:
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 {
// Given date-time string
String dateTimeStr = "Wed Aug 26 2020 11:26:46 GMT+0200";
// Define the formatter
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);
// Parse the given date-time string to java.util.Date
Date date = parser.parse(dateTimeStr);
System.out.println(date);
}
}
Output:
Wed Aug 26 10:26:46 BST 2020
Getting error
java.lang.IllegalArgumentException at java.util.Date.parse(Unknown Source) at java.util.Date.(Unknown Source)
Here is my java code
import java.util.Date;
public class DateCheck {
public static void main(String[] args) {
String dDate="Sat Apr 11 12:16:44 IST 2015";
Date cDate=null;
cDate = new Date(dDate);
}
}
I am using java 1.6
You have to use the method parse() of an implementation class of DateFormat.
The simplest way is using SimpleDateFormat.
String dDate="Sat Apr 11 12:16:44 IST 2015";
DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
Date cDate = df.parse(dDate);
Try this code:
String dDate="Sat Apr 11 12:16:44 IST 2015"
DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");
Date date = formatter.parse(dDate);
System.out.println(date);