convert string to date with locale [duplicate] - java

This question already has answers here:
Changing String date format
(4 answers)
Closed 4 years ago.
I'm trying to convert a string to date but every time i do it keeps throwing errors at me, Im not sure what i am missing
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("EEE, MMM d, yy hh:mm a", Locale.ENGLISH);
try {
// m brings in all variables from a get/setter
date = format.parse(m.getEventTime());
} catch (ParseException e) {
e.printStackTrace();
Log.d("Response.Error.Date", m.getEventTime());
}
eventTime.setText(date.toString());
My variable m.getEventTime() is passing the following string 2018-04-28 14:00:00
I have tried passing the string as 2018-04-28T14:00:00Z to no avail.
No errors are coming from the stack trace from the try/catch block but the log is printing out D/Response.Error.Date: 2017-08-19 15:00:00
when i add e.toString() to the log it prints out D/Response.Error.Date: 2017-08-19 15:00:00 java.text.ParseException: Unparseable date: "2017-08-19 15:00:00"
On the actual application when run the time is shown as now Sat Apr 28 08:22:33 GMT+01:00 2018
Am i missing something?

You can try this,
Date date = new Date();
SimpleDateFormat oldformat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat format = new SimpleDateFormat("EEE, MMM d, yy hh:mm a", Locale.ENGLISH);
try {
// m brings in all variables from a get/setter
date = oldformat.parse(m.getEventTime());
} catch (ParseException e) {
e.printStackTrace();
Log.d("Response.Error.Date", m.getEventTime());
}
eventTime.setText(format.format(date));

You can get time format like this:
String dateTime = null;
DateFormat df = new SimpleDateFormat("dd-MM-yyyy, hh:mm a");
//here you can use your required format
dateTime = df.format(new Date(stringTime));

You are converting date into English which is causing the exception:
Please Change:
SimpleDateFormat format = new SimpleDateFormat("EEE, MMM d, yy hh:mm a", Locale.ENGLISH);
eventTime.setText(date.toString());
with
SimpleDateFormat format = new SimpleDateFormat("EEE, MMM d, yy hh:mm a");
eventTime.setText(format.format(date));

Related

ParseException: Unparseable date in Java [duplicate]

This question already has answers here:
Java - Unparseable date
(3 answers)
java DateTimeFormatterBuilder fails on testtime [duplicate]
(2 answers)
Closed 3 years ago.
I need to convert String (in date format) to TimeStamp.
IN first I did like this.
private Timestamp dateConverter(String date) {
Timestamp timestamp = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm");
Date parsedDate = null;
try {
parsedDate = dateFormat.parse(date);
timestamp = new java.sql.Timestamp(parsedDate.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return timestamp;
}
Result was: ParseException: Unparseable date: "16 Jan 2020 11:02"
I tried by another way :
private Timestamp dateConverter(String date) {
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm");
LocalDateTime ldt = LocalDateTime.parse(date , f);
return Timestamp.valueOf(ldt);
}
At this time I have Internal Server Error with DateTimeParseException: Text '16 Jan 2020 11:02' could not be parsed at index 3
Your pattern can't know what is the language of your month, English, French, Arabic, Russian, Mandarin..., to solve this you have to help the formatter by using Locale like so :
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm")
.withLocale(new Locale("us"));
LocalDateTime ldt = LocalDateTime.parse("16 Jan 2020 11:02" , f); // 2020-01-16T11:02

comparing two date objects of different formats

I have two dates.
The first date is the system time. The second date is related to a news article and when the article expires, it is called end_time.
Im using selenium to test that the article does in fact expire when the system time exceed the the end_time.
My code is as follows:
String searchstring = poriginal;
//make objects to be compared
Date parsed_system_time=null;
Date parsed_end_time=null;
//generate a current time object
GenerateSimpleTime current_time = new GenerateSimpleTime();
current_time.setSystem_time_snapshot();
String system_time = current_time.getSystem_time_snapshot();
//set up the SimpleDateFormat to be used for parsing the strings into objects for comparison
//parsing the date format e.g : 04:11:2016 11:34 AM
SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yyyy hh:mm");
try{
System.out.println("Trying to parse system time: \n");
parsed_system_time = sdf.parse(system_time);
}
catch(ParseException e)
{
System.out.println("Couldnt parse system time...\n");
e.printStackTrace();
}
SimpleDateFormat end_time_sdf = new SimpleDateFormat("dd MMMM, yyyy hh:mm a");
try {
parsed_end_time = end_time_sdf.parse(end_date);
} catch (ParseException e) {
System.out.println("Couldnt parse end_date...\n");
e.printStackTrace();
}
while(parsed_system_time.before(parsed_end_time))
{
current_time.setSystem_time_snapshot();
try {
system_time = current_time.getSystem_time_snapshot();
parsed_system_time = sdf.parse(system_time);
System.out.println("endtime is: "+ parsed_end_time+"\n");
} catch (ParseException e) {
System.out.println("Couldnt parse current_time.getSystem_time_snapshot()...\n");
e.printStackTrace();
}
//System.out.println("system time is: \n");
}
When i run the program the dates are in the following format
endtime: Fri Nov 04 13:49:00 AEST 2016
systemtime: 04:11:2016 1:52 PM
if it a problem when comparing the two dates if they are in a different format. It shouldn't matter right?
When I run the test my program goes and runs indefinitely and doesnt detect when system time is greater than the end time.
The setSystem_time_snapshot() does the following:
String pattern= "dd:MM:YYY h:mm a";
SimpleDateFormat simpletime = new SimpleDateFormat(pattern);
system_time_snapshot = simpletime.format(new Date());
System.out.println("system time snapshop is "+system_time_snapshot+"\n");
Any ideas where I clean up this mess and get it working properly?
So your setSystem_time_snapshot() is returning a string in the format of
dd:MM:YYY h:mm a
But your sdf is
SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yyyy hh:mm");
If you endtime is: Fri Nov 04 13:49:00 AEST 2016,
you should use "EEE MMM dd HH:mm:ss zzzz yyyy" in your SimpleDateFormat
SimpleDateFormat end_time_sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy");

How to convert Date to a particular format in android?

"Mar 10, 2016 6:30:00 PM" This is my date and I want to convert this into "10 Mar 2016". Can I use SimpleDateFormat in android. I am not getting the exact pattern to convert it. Please help and thanks in advance
String date="Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf=new SimpleDateFormat("Some Pattern for above date");
Date newDate=spf.format(date);
spf= new SimpleDateFormat("dd MMM yyyy");
String date = spf.format(newDate);
Will this steps work? If yes, can someone please give me a pattern of that format? Thanks in advance.
This is modified code that you should use:
String date="Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf=new SimpleDateFormat("MMM dd, yyyy hh:mm:ss aaa");
Date newDate=spf.parse(date);
spf= new SimpleDateFormat("dd MMM yyyy");
date = spf.format(newDate);
System.out.println(date);
Use hh for hours in order to get correct time.
Java 8 and later
Java 8 introduced new classes for time manipulation, so use following code in such cases:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy h:mm:ss a");
LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd MMM yyyy");
System.out.println(dateTime.format(formatter2));
Use h for hour format, since in this case hour has only one digit.
conversion from string to date and date to string
String deliveryDate="2018-09-04";
SimpleDateFormat dateFormatprev = new SimpleDateFormat("yyyy-MM-dd");
Date d = dateFormatprev.parse(deliveryDate);
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE dd MMM yyyy");
String changedDate = dateFormat.format(d);
You can use following method for this problem. We simply need to pass Current date format, required date format and Date String.
private String changeDateFormat(String currentFormat,String requiredFormat,String dateString){
String result="";
if (Strings.isNullOrEmpty(dateString)){
return result;
}
SimpleDateFormat formatterOld = new SimpleDateFormat(currentFormat, Locale.getDefault());
SimpleDateFormat formatterNew = new SimpleDateFormat(requiredFormat, Locale.getDefault());
Date date=null;
try {
date = formatterOld.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
if (date != null) {
result = formatterNew.format(date);
}
return result;
}
This method will return Date String in format you require.
In your case method call will be:
String date = changeDateFormat("MMM dd, yyyy hh:mm:ss a","dd MMM yyyy","Mar 10, 2016 6:30:00 PM");
You should parse() the String into Date and then format it into the desired format. You can use MMM dd, yyyy HH:mm:ss a format to parse the given String.
Here is the code snippet:
public static void main (String[] args) throws Exception
{
String date = "Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
Date newDate = spf.parse(date);
spf = new SimpleDateFormat("dd MMM yyyy");
String newDateString = spf.format(newDate);
System.out.println(newDateString);
}
Output:
10 Mar 2016
For the sake of completeness, here is the modern version. This is for anyone reading this who either uses Java 8 or later or is happy with a (good and futureproof) external library.
String date = "Mar 10, 2016 6:30:00 PM";
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("MMM d, uuuu h:mm:ss a", Locale.ENGLISH);
DateTimeFormatter newFormatter
= DateTimeFormatter.ofPattern("d MMM uuuu", Locale.ENGLISH);
date = LocalDateTime.parse(date, parseFormatter).format(newFormatter);
System.out.println(date);
This prints the desired
10 Mar 2016
Please note the use of explicit locale for both DateTimeFormatter objects. “Mar” and “PM” both are in English, so neither the parsing nor the formatting will work unless some English-speaking locale is used. By giving it explicitly we are making the code robust enough to behave as expected also on computers and JVMs with other default locales.
To use the above on Android, use ThreeTenABP, please see How to use ThreeTenABP in Android Project. On other Java 6 and 7 use ThreeTen Backport.
You need to use SimpleDateFormat class to do the needful for you
String date = "Your input date"
DateFormat originalFormat = new SimpleDateFormat("<Your Input format here>", Locale.US)
DateFormat targetFormat = new SimpleDateFormat("<Your desired format here>", Locale.US)
Date Fdate = originalFormat.parse(date)
formattedDate = targetFormat.format(Fdate)
public static String formatDate(String fromFormat, String toFormat, String dateToFormat) {
SimpleDateFormat inFormat = new SimpleDateFormat(fromFormat);
Date date = null;
try {
date = inFormat.parse(dateToFormat);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat outFormat = new SimpleDateFormat(toFormat);
return outFormat.format(date);
}
Use:
formatDate("dd-MM-yyyy", "EEEE, dd MMMM yyyy","26-07-2019");
Result:
Friday, 26 July 2019

Not able to convert datefomat using Java [duplicate]

This question already has answers here:
Convert Date/Time for given Timezone - java
(16 answers)
Closed 8 years ago.
I have one date format in 2014-12-18T05:39:04.523Z I want to convert it into IST format.
I tried for this one.
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat targetFormat = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
Date date;
try {
//2014-12-04T12:27:15
date = originalFormat.parse("2014-12-18T05:39:04.523Z");
System.out.println("Old Format : " + originalFormat.format(date));
System.out.println("New Format : " + targetFormat.format(date));
} catch (ParseException ex) {
System.out.println("Exception *** " +ex);
}
In output:
Old Format : 2014-12-18T05:39:04
New Format : Thu Dec 18 05:39:04 IST 2014
Here instead of z, if I put Z, it is showing like this..
New Format : Thu Dec 18 05:39:04 +0530 2014
But here I want to get 11:09 like this. How can I get the result I want?
Here day month date year all are perfect, but hours minutes seconds are not correct. I have to show 11 hours 09 minutes. Why? Because I am getting this date format one greenhouse Account. This belongs to US, so I want to convert into IST Format.
When you parse the format, try small hh
When convert, try big HH
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
SimpleDateFormat targetFormat = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
In Try-Catch
targetFormat.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(targetFormat.format(date));
p/s: Import the TimeZone first...
try small hh in date format
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
SimpleDateFormat targetFormat = new SimpleDateFormat("E MMM dd hh:mm:ss z yyyy");

Date format conversion error [duplicate]

This question already has answers here:
SimpleDateFormat ignoring month when parsing
(4 answers)
Closed 9 years ago.
I am facing the problem while converting the date:
Current format is:Thu Sep 05 12:07:46 IST 2013(dow mon dd hh:mm:ss zzz yyyy)
I need to convert in to:09/04/2013 11:38 PM PDT(mm/dd/yyyy hh:mm a zzz)
But i am not able to convert.
Try using SimpleDateFormatter. You have to tell it the input/output format, you can do that based on this description (you can also find a few common examples there).
The code will be something like this:
try {
String input = "Thu Sep 05 12:07:46 IST 2013";
DateFormat formatter = new SimpleDateFormat("I leave this to you :-)))");
System.out.println(formatter.parse(input));
} catch (ParseException e) {
e.printStackTrace();
}
Hope that helps.
You can do this
TimeZone tz = TimeZone.getTimeZone("PST8PDT"); // example
// required format. Remember M is for month, m for miniute
DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm a zzz");
df.setTimeZone(tz);
String text = df.format(new Date());// current time
System.out.println(text);
Also please check this TimeZones in Java
You try to convert dateformat and timeZone as well, so you need to convert the timezone in your code.
SimpleDateFormat sf = new SimpleDateFormat("dow mon dd hh:mm:ss zzz yyyy");
isoFormat.setTimeZone(TimeZone.getTimeZone("PDT"));
Date date = isoFormat.parse("mm/dd/yyyy hh:mm a zzz");
this may help you.
try {
DateFormat dffrom = new SimpleDateFormat("E MMM dd hh:mm:ss zzz yyyy");
DateFormat dfto = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a zzz");
Date date = dffrom.parse("Thu Sep 05 12:07:46 IST 2013");
String s = dfto.format(date);
System.out.println(s);
} catch (ParseException e) {
}
OutPut
09/05/2013 00:07:46 AM IST
update
try {
DateFormat dffrom = new SimpleDateFormat("E MMM dd hh:mm:ss zzz yyyy");
DateFormat dfto = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a zzz");
TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles");
dfto.setTimeZone(zone);
Date date = dffrom.parse("Thu Sep 05 12:07:46 IST 2013");
String s = dfto.format(date);
System.out.println(s);
} catch (ParseException e) {
}
output
09/04/2013 11:37:46 AM PDT

Categories

Resources