Selecting Date format based on the string [duplicate] - java

This question already has an answer here:
Fri Mar 30 00:00:00 CET 14 to dd/mm/yyyy
(1 answer)
Closed 5 years ago.
I have class which receives Date in string format from other class. It is now receiving two different formats
Format 1: YYYY_MM_DD
Format 2: EEE MMM dd HH:mm:ss z yyyy
now I want to write a method which receives this string and convert it into required format like this 'DDMMMYYYY '

You can try brute force to parse catching the exceptions:
edit:
using the java8 API (adapt the format as you need/want)
public String convertDateFormatJ8(String format) {
String retFormat = "ddMMyyy";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("[yyyy_dd_MM][yyyy-MM-dd HH:mm]");
try {
LocalDateTime localDate = LocalDateTime.parse(format, formatter);
return localDate.format(DateTimeFormatter.ofPattern(retFormat));
} catch (DateTimeParseException ex) {
System.err.println("impossible to parse to yyyy-MM-dd HH:mm");
}
try {
LocalDate localDate = LocalDate.parse(format, formatter);
return localDate.format(DateTimeFormatter.ofPattern(retFormat));
} catch (DateTimeParseException ex) {
System.err.println("impossible to parse to yyyy_dd_MM");
}
return null;
}
for old java versions
public String convertDateFormat(String format) {
DateFormat df1 = new SimpleDateFormat("YYYY_MM_DD");
DateFormat df2 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
DateFormat dfResult = new SimpleDateFormat("DDMMMYYYY ");
Date d = null;
try {
d = df1.parse(format);
return dfResult.format(d);
} catch (ParseException e) {
System.err.println("impossible to parse to " + "YYYY_MM_DD");
}
try {
d = df2.parse(format);
return dfResult.format(d);
} catch (ParseException e) {
System.err.println("impossible to parse to " + "EEE MMM dd HH:mm:ss z yyyy");
}
return null;
}
if you give any other invalid string, the string returned will be null!

You can use this approach and declare optional section in pattern :
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("[yyyy_MM_dd][EEE MMM dd HH:mm:ss Z yyyy]", Locale.ENGLISH);
This formatter will parse date for both patterns and then you can easily convert it to required format.
P.S. I've tested it but not sure which date should be parsable for EEE MMM dd HH:mm:ss Z yyyy template. So just play with it and use Java 8 approaches (Java Time)

Related

convert date in android [duplicate]

This question already has answers here:
How to parse month full form string using DateFormat in Java?
(4 answers)
Closed 2 years ago.
I want to convert this date but parse exemption it should be like this result "2019-12-28 14:00:00"
try {
String strCurrentDate = "April 08 2020 4:24 AM"
SimpleDateFormat format = new SimpleDateFormat("MMM dd yyyy hh:mm a");
Date newDate = format.parse(strCurrentDate);
format = new SimpleDateFormat("MMM dd,yyyy hh:mm a");
String date = format.format(newDate);
Log.d("datessscc", date);
} catch (ParseException e) {
e.printStackTrace();
}
Please change your SimpleDateFormat
Try This:
SimpleDateFormat input = new SimpleDateFormat("MMM dd yyyy hh:mm a");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date getAbbreviate=input.parse("May 22 2020 4:22 AM"); // parse input
Log.i("ouput_Date", "onCreate: "+output.format(getAbbreviate)); // format output
String date=output.format(getAbbreviate);
} catch (ParseException e) {
e.printStackTrace();
}

Why is the date unparseable [duplicate]

This question already has answers here:
java.text.ParseException: Unparseable date
(10 answers)
Closed 3 years ago.
I'm attempting to parse a new Date object, but I keep hitting the following error.
W/System.err: java.text.ParseException: Unparseable date: "Thu May 16 09:28:39 GMT+01:00 2019"
I've attempted various different patterns for dateFormat, but nothing seems to work.
This is where the error is.
c.setTime(dateFormat.parse(oldDate));
Code
public static String addDay(int numberOfDays) {
String oldDate = String.valueOf(new Date());
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy'T'HH:mm:ss", Locale.ENGLISH);
Calendar c = Calendar.getInstance();
try {
c.setTime(dateFormat.parse(oldDate));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DAY_OF_YEAR,numberOfDays);
dateFormat=new SimpleDateFormat("dd-MM-yyyy'T'HH:mm:ss", Locale.ENGLISH);
Date newDate=new Date(c.getTimeInMillis());
String resultDate=dateFormat.format(newDate);
return resultDate;
}
Try This function
In your question you are converting Date to string
then after you are once again Parsing String to Date
that is very Long way. you can directly set as
c.setTime(oldDate);
public static String addDay(int numberOfDays) {
Date oldDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy'T'HH:mm:ss", Locale.ENGLISH);
Calendar c = Calendar.getInstance();
c.setTime(oldDate);
c.add(Calendar.DAY_OF_YEAR,numberOfDays);
dateFormat=new SimpleDateFormat("dd-MM-yyyy'T'HH:mm:ss", Locale.ENGLISH);
Date newDate=new Date(c.getTimeInMillis());
String resultDate=dateFormat.format(newDate);
return resultDate;
}
The pattern should be like :
SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH);
Then to print you need a second SimpleDateFormat:
Date parsedDate = sdf.parse(date);
SimpleDateFormat print = new SimpleDateFormat("MMM d, yyyy HH:mm:ss");
System.out.println(print.format(parsedDate));
Your pattern is wrong. You should use EEE MMM dd HH:mm:ss z yyyy

SimpleDateFormat returning null but can print date on screen

I have a bit of a dilemma. I have a method that's supposed to convert a given string to the type Date. For some reason I can print out the Date on the screen however the parser returns null when I try to retreive the date from the method.
An example string that is used as the parameter: Thu Aug 10 07:23:00 EEST 2017
public Date convertStringToDate(String sDate) {
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy", Locale.getDefault());
try {
Date date = format.parse(sDate);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
You are declaring a second variable named date in your try body. Remove the Date portion (which makes it local). Change
Date date = format.parse(sDate);
to
date = format.parse(sDate);
(Posted on behalf of the OP.)
I had declared the date variable somewhere outside the method and to solve this problem I had to declare a local one. Down below is the updated working code:
public Date convertStringToDate(String sDate) {
Date date;
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy", Locale.getDefault());
try {
date = format.parse(sDate);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}

How to format 2016-02-12T15:23:20+02:00 time [duplicate]

This question already has answers here:
Illegal pattern character 'T' when parsing a date string to java.util.Date
(4 answers)
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 7 years ago.
I'm getting the above Date format from our webservice. I have an idea on how to format the date, im just having issues with the fact it comes down as a string.
I have tried this but I need to return it as a String, which in a way isn't a problem.
This is what I have tried but it throws an Exception:
java.text.ParseException: Unparseable date:
"2016-02-26T00:00:00+02:00" (at offset 4)
Code:
public static String formatDate(String unFormattedTime) {
String formattedTime;
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM HH:mm");
Date date = sdf.parse(unFormattedTime);
formattedTime = sdf.format(date);
return formattedTime;
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}
How could I format it in a format like dd MMM HH:mm?
Here you are with a working snippet of what you want to achieve:
public class FormatDateExample {
public static void main(String[] args) {
String date = "2016-02-26T00:00:00+02:00";
System.out.println(formatDate(date));
}
public static String formatDate(String unFormattedTime) {
String formattedTime;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = sdf.parse(unFormattedTime);
sdf = new SimpleDateFormat("dd MMM HH:mm");
formattedTime = sdf.format(date);
return formattedTime;
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}
}
First you have to parse the date with the given format you have
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = sdf.parse(unFormattedTime);
Then you have to format that date to the desired format "dd MMM HH:mm"
sdf = new SimpleDateFormat("dd MMM HH:mm");
formattedTime = sdf.format(date);
If you are using Java 8 you can try this:
LocalDate parsedDate = LocalDate.parse(unFormattedTime, ISO_OFFSET_DATE_TIME)
Ref:
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_OFFSET_DATE_TIME

date format in java

My requirement is to get the date in format MM/dd/yy. But I am currently getting the date value as "Sun Dec 31 00:00:00 IST 2006". I tried a sample code for the conversion as follows.
String pattern = "MM/dd/yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("12/31/2006");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
Please help me to convert the given date into MM/dd/yy
You need to use SDF (SimpleDateFormat) to process the output too.
String pattern = "MM/dd/yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("12/31/2006");
System.out.println(format.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Change your code to:
String pattern = ;
SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat outputFormat = new SimpleDateFormat("MM/dd/yy");
try {
Date date = inputFormat.parse("12/31/2006");
System.out.println(outputFormat.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
The reason of your output is because you're outputting the date object through System.out.println(date); which is effectively, translated to System.out.println(date.toString());
The toString() method of Date outputs date in the format of:
EEE MMM dd HH:mm:ss zzz yyyy
Here's the code for Date.toString()
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == gcal.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
Your code is correct though. Use SimpleDateFormat to display the date like so:
System.out.println(format.format(date));
You're using the SimpleDateFormat to parse a string, and that's working fine - but then you're using Date's toString method (implicitly) when formatting the date. That will use a default format which is completely independent of the format which was originally used to parse the value.
A Date object knows nothing about how you want to format it. That's what you should be using SimpleDateFormat for.
You can use SimpleDateFormat to format it again:
System.out.println(format.format(date));
... but a better approach would be to switch to Joda Time and use its DateTimeFormatter class, which is thread-safe and immutable, unlike SimpleDateFormat... the rest of its API is better, too.

Categories