how to get am/pm using simple date format - java

I want to get 12 hour clock time from milliseconds.I tried as follows
public class GetTimeFormat{
static SimpleDateFormat format;
public static String convertDate(String dateformat,Long date){
format = new SimpleDateFormat(dateformat);
String formattedDate = format.format(date);
return formattedDate;
}
public static void main(String args[])
{
long cal=1386059340010l;
String dateString=convertDate("MMM dd,yyyy HH:mm:ss a", cal);
System.out.println(dateString);
}
}
The corresponding date for the above milliseconds is Tue Dec 03 13:59:00 IST 2013
So I thought I will get formatted date as Dec 03,2013 1:59:00 PM
but instead I am getting Dec 03,2013 13:59:00 PM
there is no need for am/pm in 24 hour clock and in 12 hour clock am/pm is required
But In my way I am getting time in 24 hour format + PM.
Can Any body tell me whats the mistake here?
Another question is why in ideone its showing Dec 03,2013 08:29:00 AM
Not only in ideone but I have checked many online compilers and every where its showing the same but in local machine time is different(13:59)

You need to use a lowercase h in your format pattern:
String dateString = convertDate("MMM dd,yyyy h:mm:ss a", cal);
You can see here for a full reference of format patterns, including an example that covers this specific case.

Related

SimpleDateFormat parse not honouring timezone

public static void main(String[] args) throws ParseException {
SimpleDateFormat dt = new SimpleDateFormat("MM dd yy");
dt.setLenient(false);
dt.setTimeZone(TimeZone.getTimeZone("Asia/Hong_Kong"));
Date date = dt.parse("05 14 16");
System.out.println(date);
}
Output: Fri May 13 21:30:00 IST 2016
If i try to use the output it is switching to one day before instead of the correct day.
Is this expected or an issue with the API?
This is expected and there is no bug in Java.
Class Date does not contain timezone information. A java.util.Date is nothing more than wrapper for a number of milliseconds since 01-01-1970, 00:00:00 GMT. It does not remember that the string that it was parsed from contained information about a timezone.
When you display a Date, for example by (implicitly) calling toString() on it as you are doing here:
System.out.println(date);
it will be printed in the default timezone of your system, which is IST in your case.
If you want to print it in a certain timezone, then format it using a SimpleDateFormat object, setting the desired timezone on the SimpleDateFormat object. For example:
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss Z");
df..setTimeZone(TimeZone.getTimeZone("Asia/Hong_Kong"));
System.out.println(df.format(date));

Converting Date to LocalDate returning strange results around 200AD

I'm getting inconsistent results when converting Dates to LocalDates, around the year 200. Using the following code to do the conversion:
private LocalDate toLocalDate(Date localDate)
{
return LocalDateTime.ofInstant(localDate.toInstant(), ZoneId.systemDefault()).toLocalDate();
}
My ZoneId.systemDefault() is Africa/Harare, which matches the CAT used in the test. The test case I run is
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
String dateString = "Tue Jan 01 00:00:00 CAT 200";
String dateString2 = "Tue Jan 01 00:00:00 CAT 201";
String dateString3 = "Wed Dec 31 00:00:00 CAT 200";
System.out.println(toLocalDate(simpleDateFormat.parse(dateString)));
System.out.println(toLocalDate(simpleDateFormat.parse(dateString2)));
System.out.println(toLocalDate(simpleDateFormat.parse(dateString3)));
My expected output for this would be
0200-01-01
0201-01-01
0200-12-31
Or, if not that, at least consistently incorrect values. The actual results are
0199-12-31
0201-01-01
0200-12-31
So it seems that the first one is being rolled back slightly, possibly the two hours corresponding to the CAT timezone? But why does this only happen on the one case? Doing the same experiment with the year 2000 does not produce the same error.
Stephen has provided an explanation in the comment. Basically, java.util.Date uses a calendar system which cuts over between the Julian calendar system and the Gregorian calendar system in 1582, skipping 10 days. So dates in 1582 or before will exhibit discrepancies - but the size of the discrepancy will vary over time - by 3 days every 400 years, on average. It so happens that between 200 and 400AD, you don't see this because that corresponds to when the discrepancy is 0.
Here's a short but complete program to demonstrate the problem:
import java.time.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
// Value obtained with Noda Time: should be 0199-12-31T22:00:00Z.
long millis = -55855792800000L;
Instant instant = Instant.ofEpochMilli(millis);
Date date = new Date(millis);
System.out.println(instant);
System.out.println(date);
}
}
Output on my machine:
0199-12-31T22:00:00Z
Tue Jan 01 22:00:00 GMT 200
This is all complicated by the problems in your initial code of assuming CAT and Africa/Harare are the same (at that point in time, Africa/Harare is regarded as having an offset of +02:10) and the incorrect day names in your strings - but it's the bug in Java which is causing the issue here.
I suggest you perform all your parsing using the java.time.format classes - then I'd hope you won't get this inconsistency.

SimpleDateFormat function parse(String s) gives wrong date

As an input I have Date object(for example, exDate=Fri Aug 01 00:00:00 EEST 2014) that must be formated. After the parsing of the date, I get wrong date.
SimpleDateFormat sdf = new SimpleDateFormat(
"dd-MMM-YYYY hh.mm.ss.SSSSSSSSS aa", Locale.ENGLISH);
String dateStart = sdf.format(exDate);
Date dateF = sdf.parse(dateStart);
dateStart will be equal to
01-Aug-2014 12.00.00.000000000 AM
and the resut, dateF will be equal to
Sun Dec 29 00:00:00 EET 2013
So, after the parsing of a string with date, the result is wrong.
Maybe, somebody know the source of the problem? Or another way to format date in another SimpleDateFormat?
The problem is the YYYY which means:
Y Week year;
The actual year, which is what you are looking for would be yyyy.
I really recommend that you go in the link above to see the full list.
You should also replace the milliseconds to .SSS as you can't get more precise than that.

Grab exact date without timezone interfering with XMLGregorianCalendar in Java

I have a XMLGregorianCalendar that I would like to convert to a Java Date object, but when I try to covert this:
2013-11-19T00:00:00-00:00
I always get a date with the value a day behind.
Mon Nov 18 17:00:00 MST 2013
I just want a date object containing 11/19/2013.
As commented above, the result you're getting is right - it's the same moment in time. Midnight UTC is 5PM MST the day before. Perhaps you should look into why your time is in "-00:00" instead of "-07:00" (MST)... but in the meanwhile, I suppose you could try this:
public static void main(String... args) throws DatatypeConfigurationException {
XMLGregorianCalendar xcal = DatatypeFactory.newInstance().newXMLGregorianCalendar("2013-11-19T00:00:00-00:00");
Calendar c = xcal.toGregorianCalendar();
c.setTimeZone(TimeZone.getDefault());
Date d = c.getTime();
System.out.println(d);
}
prints out Tue Nov 19 00:00:00 EST 2013, and will work for other times of day, not just midnight.
I just did this,
Date startDate = new Date(request.getStartTime().getYear(), request.getStartTime().getMonth(), request.getStartTime().getDay(), 0, 0, 0);

SimpleDateFormat parse function changing the format

I have a String with several dates:
[20-Jul-2012 5:11:36,670 UTC PM, 20-Jul-2012 5:11:36,683 UTC PM]
ParsePosition parsePos = new ParsePosition(1);
SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss,SSS z a");
System.out.println(format2.parse(entry.getValue().toString(), parsePos)) ;
Output : Fri Jul 20 06:11:36 BST 2012
I need the output to be 20-Jul-2012 5:11:36,670 UTC PM.
Do I need to set a LOCALE in the SimpleDateFormat to not have a different output?
You need to set the time zone, but more importantly, you simply need to actually use the format to format the date:
Date date = format2.parse(...);
String formattedDate = format2.format(date);
System.out.println(formattedDate);
What your code does is:
Date date = format2.parse(...);
System.out.println(date.toString());
I don't really understand the point in parsing a string to a date, and then displaying the date using the exact same format, though (except to validate that the String is indeed a valid date, but then you could simply reuse the original string).
You've got two small problems:
Use hh for the hour, not HH. H is "Hour in day (0-23), and so will not work correctly with a, the AM/PM marker. Your two example date strings will parse to AM, not PM.
You're using SimpleDateFormat to parse the string, but not format it. Use format2.format(format2.parse(entry.getValue().toString()).
Here's a complete example:
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss,SSS z a");
String input = "20-Jul-2012 5:11:36,670 UTC PM";
Date date = format.parse(input);
String output = format.format(date);
System.out.println(output);
Result:
20-Jul-2012 05:11:36,670 UTC PM

Categories