My first attempt was:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Date date = formatter.parse(string);
It throws ParseException, so I found this hack:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
TimeZone timeZone = TimeZone.getTimeZone("Etc/GMT");
formatter.setTimeZone(timeZone);
Date date = formatter.parse(string);
It did not work either, and now I'm stuck. It parses without problems if I just change the timezone to "GMT".
edit: An example string to parse would be "2011-11-29 10:40:24 Etc/GMT"
edit2: I would prefer not to remove timezone information completely. I am coding a server that receives the date from an external user, so perhaps other dates will have other timezones.
To be more precise: This specific date I receive is from the receipt from the apple server after making an in app purchase on an iphone app, but I could also receive dates from other sources.
Don't know if this question is still relevant to you, but if you use Joda time, this'll work:
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss ZZZ").parseDateTime(s)
Without Joda time the following will work (bit more work though):
String s = "2011-11-29 10:40:24 Etc/GMT";
// split the input in a date and a timezone part
int lastSpaceIndex = s.lastIndexOf(' ');
String dateString = s.substring(0, lastSpaceIndex);
String timeZoneString = s.substring(lastSpaceIndex + 1);
// convert the timezone to an actual TimeZone object
// and feed that to the formatter
TimeZone zone = TimeZone.getTimeZone(timeZoneString);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(zone);
// parse the timezoneless part
Date date = formatter.parse(dateString);
It didn't work for me either the thing is I tried setting TimeZone of SimpleDateFormatter to "Etc/GMT" and then formatted a new date here is the output:
2011-11-30 10:46:32 GMT+00:00
So Etc/GMT is being translated as GMT+00:00
If you really want to stick to parse "2011-09-02 10:26:35 Etc/GMT" then following will help too without even considering explicit Timezone change:
java.text.SimpleDateFormat isoFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'Etc/GMT'");
isoFormat.parse("2010-05-23 09:01:02 Etc/GMT");
Works fine.
Following code is working for me
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Etc/GMT"));
try { System.out.println( sdf.parse("2011-09-02 10:26:35 Etc/GMT") );
} catch (ParseException e){
e.printStackTrace();
}
Related
I am getting the json response as "publishedAt": "2017-09-12T01:03:08Z"
and i want to format this response in simple date likeAug 12-09-2017 3:08and set it into TextView
i am using something like this
Date dateObj = new Date(currentNews.getTimeInString());
TextView dateAndTimeView = (TextView) listItemView.findViewById(R.id.date_and_time);
String formattedDateAndTime = formatDateAndTime(dateObj);
dateView.setText(formattedDate);
private String formatDateAndTime(Date dateObj){
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM, yyyy");
return dateFormat.format(dateObj);
}
Did you tried SimpleDateFormat?
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Something like (pseudocode, can`t test it here)
String givenDate = "2017-09-12T01:03:08Z";
SimpleDateFormat sdf= new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
try {
Date date = sdf.parse(givenDate );
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
Please use this method:
public String getDateFromUTC(String ourDate)
{
try
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(ourDate);
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy hh:mm aa"); //this format changeable
dateFormatter.setTimeZone(TimeZone.getDefault());
ourDate = dateFormatter.format(value);
//Log.d("OurDate", OurDate);
}
catch (Exception e)
{
ourDate = "00-00-0000 00:00";
}
return ourDate;
}
TL;DR
String formattedDateAndTime = Instant.parse("2017-09-12T01:03:08Z")
.atZone(ZoneId.of("America/Nome"))
.format(DateTimeFormatter.ofPattern("EEE dd-MM-uuuu H:mm", Locale.ENGLISH));
Time zone is crucial
As the code stands, it produces Mon 11-09-2017 17:03. However, please substitute the correct region and city for your desired time zone, and this will be reflected in the output. If you want to use the JVM’s time zone setting, use ZoneId.systemDefault(); however, be warned that other code running in the JVM may change this setting outside of your control, so it’s not perfectly reliable.
ThreeTenABP
I have taken my own medicine from my comment: thrown away Date and SimpleDateFormat. So the above code requires ThreeTenABP. All the details are in this question: How to use ThreeTenABP in Android Project.
ISO 8601
I am further exploiting the fact that the string from you JSON response is in ISO 8601 format, which the modern date and time classes “understand” as their default. Had it been in some other format, a separate DateTimeFormatter would have been needed for parsing it; but not here (with the outdated classes, two different SimpleDateFormats would be needed).
Try this code .
SimpleDateFormat formatter = new SimpleDateFormat(" EEE dd-MM-yyyy HH:mm");
I am working in date conversion in java in that i am using following code snippet to convert the UTC time to IST format.It is working properly in the local when i run it but when i deploy it in server its not converting , its displaying only the utc time itself.Is there any configuaration is needed in server side.Please help me out.
CODE SNIPPET:
DateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String pattern = "dd-MM-yyyy HH:mm:ss";
SimpleDateFormat formatter;
formatter = new SimpleDateFormat(pattern);
try {
String formattedDate = formatter.format(utcDate);
Date ISTDate = sdf.parse(formattedDate);
String ISTDateString = formatter.format(ISTDate);
return ISTDateString;
}
Java Date objects are already/always in UTC. Time Zone is something that is applied when formatting to text. A Date cannot (should not!) be in any time zone other than UTC.
So, the entire concept of converting utcDate to ISTDate is flawed.
(BTW: Bad name. Java conventions says it should be istDate)
Now, if you want the code to return the date as text in IST time zone, then you need to request that:
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata")); // Or whatever IST is supposed to be
return formatter.format(utcDate);
Using Java 8 New API,
Instant s = Instant.parse("2019-09-28T18:12:17Z");
ZoneId.of("Asia/Kolkata");
LocalDateTime l = LocalDateTime.ofInstant(s, ZoneId.of("Asia/Kolkata"));
System.out.println(l);
I am trying to take date in string and its input format string and converting the date in output format. However after conversion into Date, the java code increases the number of hours by one. I am not able to understand what causes the bug.
My Code:
try {
DateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
DateFormat inputFormat = new SimpleDateFormat(format);
Date date = inputFormat.parse(parameterValue);
parameterValue = outputFormat.format(date);
return parameterValue;
} catch (ParseException ex) {
// take action
}
format string: ddMMMyyyy / hh:mm z
Input Date: 07DEC2015 / 10:02 GMT
Output Date: 07/12/2015 11:02:00
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
resolved it.
If you don't want to use timezone, in java 8 you can use LocalDate/LocalTime/LocalDateTime:
LocalDateTime localDateTimeInstance = LocalDateTime.parse(dateToBeConverted, DateTimeFormatter.ofPattern(formatOfDateToBeConverted));
return localDateTimeInstance.format("dd/MM/yyyy hh:mm:ss");
/*
Also check out ZoneDate, ZoneTime (for timezone)
Checkout - LocalDate, LocalTime
*/
I have below code snippet
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss.SSS");
String processedContentDate="2012-04-10 12:53:28.033";
java.util.Date parsedDate = dateFormat.parse(processedContentDate);
java.sql.Timestamp timestamp = new java.sql.Timestamp(
parsedDate.getTime());
I get parsed date as Tue Apr 10 00:53:28 IST 2012 and timestamp as 2012-04-10 00:53:28.033 . i want to get the time exactly as 12:53:28.033(as in my original string)
not 00:53:28.033. Not getting why 12:53:28 is getting converted to 00:53:28. what should I do to get 12:53:28?
EDIT: After getting the response, I tried this small programme where current time is 14:34:38.899
but at both lines i.e at line 1 and line 2, I got below parsed date
2012-04-10 14:34:38.899
As per reply I should have got 02:34:38.899 at line 1 as date format is yyyy-MM-dd hh:mm:ss.SSS")
java.util.Date date= new java.util.Date();
String strDate=date.toString();
java.util.Date parsedDate;
java.util.Date parsedDate2;
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss.SSS");// line 1
SimpleDateFormat dateFormat2 = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");//line 2
try {
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
strDate=timestamp.toString();
parsedDate = dateFormat.parse(strDate);//line1
parsedDate2 = dateFormat2.parse(strDate);//line2
Define your dateFormat like that
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
HH instead of hh. See SimpleDateFormat
Your date format must be yyyy-MM-dd HH:mm:ss.SSS.
hh is hours in am/pm, while HH is hours in a day (that's where you mistake is). See SimpleDateFormat.
As per definition of Date.toString() and Timestamp.toString, the .toString() output is always using a 24-hour clock. If you want to show the time using AM/PM, you should use the dateformatter to print the date. As you are using the same date/time as a source for both (strDate will use 14:34), when you parse the date, the SimpleDateFormat using the 12-hour clock is "lenient" and allows parsing of 14 as an hour.
If you set
dateFormat.setLenient(false);
you'll probably find that the dateFormat.parse(strDate) will fail.
To print dates, I would never rely on toString, but always use a formatter.
System.out.println(dateFormat.format(parsedDate)); // should show ...02:36...
System.out.println(dateFormat2.format(parsedDate)); // should show ...14:36...
System.out.println(dateFormat.format(parsedDate2)); // should show ...02:36...
System.out.println(dateFormat2.format(parsedDate2)); // should show ...14:36...
Try below code:
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = fmt.parse("yourdate");
SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy hh:mm a");String myDate = fmtOut.format(date);
If yourdate is 2016-06-10 12:06:43, then output will be 10-06-2016 12:06 pm.
I'm having a hard time Parsing/Formatting a Date string received back from a web service. I've attempted multiple approaches, but with no luck.
Sample Date String:
2011-10-05T03:00:00Z
Exception:
W/System.err(10072): java.text.ParseException: Unparseable date: "2011-10-05T05:00:00Z" (at offset 10)
W/System.err(10072): at java.text.DateFormat.parse(DateFormat.java:626)
Sample Code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:SSSS");
Date date = formatter.parse(info.AiringTime);
I've found that if I remove the "T" between the date and the time and replace it with a space, it will format just fine. Anybody have any suggestions?
--UPDATE--
After looking deeper into the API documentation, I found this:
All response DateTime values are in UTC format. You need to apply the UTC offset to calculate the local time for display.
DateTime is a date-and-time value specified in one of the following formats:
UTC format: YYYY-MM-DDThh:mm:ssZ. For example: 2011-03-15T02:00:00Z.
Local time with an offset: YYYY-MM-DDThh:mm:ss + or - hh:mm (positive or negative offset). For example, for US Pacific time: 2011-03-14T06:00:00 -08:00.
Any suggestions on the UTC format approach?
You could try:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = dateString.replace("Z", "GMT+00:00");
Date date = dateFormat.parse(dateString);
The above code should correctly handle the case where a timezone is specified in the date. As Z represents the UTC/GMT timezone it is replaced by GMT so the SimpleDateFormat can interpret it correctly (i would love to know a cleaner way of handling this bit if anyone knows one).
Try,
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
This pattern should parse the date you provide: "yyyy-MM-dd'T'HH:mm:ss'Z'".
If you want to use SimpleDateFormat and you have a limited number of variations, you can create separate formatters for each pattern and chain them:
Date date = formatter1.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter3.parse(info.AiringTime);
}
}
}
or put them in a list and iterate until non-null or no more formatters.
If you have too many patterns for this to be practical, you can parse it yourself or try one of these libraries.
This worked for me
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}