Java format milliseconds to uu:mm:ss - java

I have the following problem and I couldn't find the best solution for it yet.
Lets say I have an integer with the following value:
int miliseconds = 65111;
I want to print it to an stream using the printf() function. Is there a way I can do the following:
printf("Time: %uu:mm:ssT", miliseconds");
so it will return:
Time: 00:01:05
Here I just made up the %uu:mm:ssT part, but is there a way to do this.
Also, do you know a website where I can find all the formatting options, so I can look it up myself next time.

Use
final int miliseconds = 65111;
System.out.printf("%1$TM:%1$TS.%1$TL\n", (long) miliseconds);
and see Format String Syntax for details.

Have a look at the SimpleDateFormat feature.
Consider the following sample
String inputPattern = ....
String outputPattern = ....
String ms = ((Integer) milliseconds).toString();
DateFormat inFormat = new SimpleDateFormat(inputPattern);
DateFormat outFormat = new SimpleDateFormat(outputPattern);
// Parse input
Date date = inFormat.parse(ms);
// Format the output
String output = outFormat.format(date);
[Edit] - Updated sample to only use j2se instead of including yodatime.

If you use the SimpleDateFormat to format a time from new Date(milliseconds), don't forget that SimpleDateFormat is time zone sensitive. So set it to UTC before using, like this:
DateFormat outFormat = new SimpleDateFormat("HH:mm:ss");
outFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date d = new Date(milliseconds);
String result = outFormat.format(d);
(I'm using a similar code in my program for a JSpinner to input a millisecond time value.)

Related

SimpleDateFormat can not parse string to Date

I'm so ashamed asking this question, but I have no other choice.
I want to convert this string to date:
2015-11-25T19:36:39.571+06:00
To convert it I use SImpleDateFormat:
String str = "2015-11-25T19:36:39.571+06:00";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = format.parse(str);
System.out.println(date);
When I launch this code it gives to me java.text.ParseException: Unparseable date: exception.
I don't know why this is happening.
This should work (In java 7)
String str = "2015-11-25T19:36:39.571+06:00";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
Date date = format.parse(str);
System.out.println(date);
XXX is available in Java 7 as Timezone offset, see the Javadoc http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
The issue is because of wrong pattern used.Z isInstead of yyyy-MM-dd'T'HH:mm:ss.SSSZ use pattern yyyy-MM-dd'T'HH:mm:ss.SSSX
Z represents Time zone in RFC 822 time zone format i.e., like this -0800
So, your code will look like this.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Your pattern does not correspond entirely to the input string, you have a slight type in the time zone part of your format.
Change your format in the following way to make it work:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Or change your input string to:
String str = "2001-07-04T12:08:56.235-07:00";
Please use Below Pattern it works fine
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
There is a problem with your input String according to the pattern you have used.
remove the last ':' from the str variable.
change:
String str = "2015-11-25T19:36:39.571+06:00";
in to:
String str = "2015-11-25T19:36:39.571+0600";
and run. It'll work.
Here is the fiddle:
working link

java date and time from timestamp

I am working on android app with achartengine where I am making a TimeSeries linegraph. I have stored all my variables inside an Arraylist. Since I need correct date object to insert in the time axis of my chart I am using,
int count = list.size();
Date[] dt = new Date[count];
for(int i=0;i<count;i++){
long a = Long.parseLong(list.get(i).get("time"));
dt[i] = new Date(a);
}
Here long a has the timestamp . With above piece of code. I am able to get dt as 09-Apr-2014 but I need the date to be shown as 09-Apr 12:55 . How can I do that,
I tried using the folllowing
SimpleDateFormat sdfDate = new SimpleDateFormat("MM-dd HH:mm");
Date now = new Date();
String strDate = sdfDate.format(now);
But Since strDate is a string I cannot use it as dt[i] = strDate which will throws an error as one is Date and another is String.
How can I solve this ?
Thanks
You can solve it this way:
dt[i] = sdfDate.parse(strDate);
If you really just need the date strings, you can do this:
int count = list.size();
String[] dt = new String[count];
for (int i = 0; i < count; i++) {
long a = Long.parseLong(list.get(i).get("time"));
Date d = new Date(a);
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm");
dt[i] = dateFormat.format(d);
}
Or, if you actually need the Date array, just format the dates on the fly as you need them.
Your question is misguided - you are showing how you create Date objects in the code, yet what you want to fix is how you show them.
The Date array will have dates precisely to the millisecond. The default toString() method of the Date objects shows only the day, that's why you're not seeing the time.
It is inherently the UIs responsibility to decide on the format of time that it is going to print, hence you should pass the Date array to the UI (or up to the point of printing) and format them there.
The DateFormat can do both (date to string representation and back):
DateFormat formatter = new SimpleDateFormat( "dd-MM-yyyy HH:mm:ss" );
Date to String:
Date date = new Date();
String sDate = formatter.format( time );
String to Date:
Date date = formatter.parse(sDate );
When you store the date, you should store it as precise as possible (milliseconds). For displaying it as a string, you can use whatever format you want.

PHP timestamp to Java timestamp

I need to convert this 1384174174 timestamp from PHP to Java. This is how I echo the date('Y/m/d H:i:s' ,$dn1['timestamp'] in PHP yet I don't know how to do it in Java. Please help me. Thanks.
In Java, you'd do it like this:
Date date = new Date(1384174174);
SimpleDateFormat f = new SimpleDateFormat("Y/M/d H:m:s");
String dateFormatted = f.format(date);
Watch out for the format pattern where, unlike PHP, M is month in year and m is minute in hour.
This method will take your Unix style date and create a Java Date. It returns a readable string. It should help you get started.
private String unixToString(long unixSeconds) {
Date date = new Date(unixSeconds);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}

Simple question about java SimpleDateFormat

This will probably be a dumb question, but I don't understand the java date function. Here is some code:
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
Date s = sdf.parse(var);
Calendar scal = java.util.GregorianCalendar.getInstance();
scal.setTime(s);
Log.w("Time: ", Long.toString(s.getTime()));
If var = "10:00" I get "64800000".
If var = "11:00" I get "68400000".
If var = "12:00" I get "28800000".
If var = "13:00" I get "75600000".
If var = "14:00" I get "79200000".
If var = "00:00" I get "28800000".
What is up with 12:00? Why, when var=12:00 do I get the same result as when it's 00:00? All the other results seem correct. I obviously don't understand the java date function, but I can't seem to find any explanation for this anywhere. This is screwing up my time span calculator.
If you want to use 24-hour time, you need to use the capital HH format:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
I should have used "H" instead of "h". "h" is for am/pm format.

java date format incompatible with xquery xs:date format, how to fix?

In java, when using SimpleDateFormat with the pattern:
yyyy-MM-dd'T'HH:mm:ss.SSSZ
the date is outputted as:
"2002-02-01T18:18:42.703-0700"
In xquery, when using the xs:dateTime function, it gives the error:
"Invalid lexical value [err:FORG0001]"
with the above date. In order for xquery to parse properly, the date needs to look like:
"2002-02-01T18:18:42.703-07:00" - node the ':' 3rd position from end of string
which is based on the ISO 8601, whereas Java date is based on the RFC 822 standard.
I would like to be able to easily specify the timezone in Java so that it will output the way that xquery wants.
Thanks!
OK, the linked to forum post DID help, thank you. I did however find a simpler solution, which I include below:
1) Use Apache commons.lang java library
2) Use the following java code:
//NOTE: ZZ on end is not compatible with jdk, but allows for formatting
//dates like so (note the : 3rd from last spot, which is iso8601 standard):
//date=2008-10-03T10:29:40.046-04:00
private static final String DATE_FORMAT_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ";
DateFormatUtils.format(new Date(), DATE_FORMAT_8601)
Great find regarding commons.lang.java! You can even save yourself from creating your own format string by doing the following:
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(new Date());
Well, I did run into a problem - it doesn't appear to me (and I could be wrong) that there was any way to convert from and ISO string that DateUtils (from apache commons lang) creates, back to a date!
ie. apache commons will format it the way I would like, but not convert it back to a date again
So, I switched to JodaTime, and its much easier since its based on ISO8601 - here is the code:
public static void main(String[] args) {
Date date = new Date();
DateTime dateTime = new DateTime(date);
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
String dateString = fmt.print(dateTime);
System.out.println("dateString=" + dateString);
DateTime dt = fmt.parseDateTime(dateString);
System.out.println("converted date=" + dt.toDate());
}
Try this:
static public String formatISO8601(Calendar cal) {
MessageFormat format = new MessageFormat("{0,time}{1,number,+00;-00}:{2,number,00}");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df.setTimeZone(cal.getTimeZone());
format.setFormat(0, df);
long zoneOff = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET) / 60000L;
int zoneHrs = (int) (zoneOff / 60L);
int zoneMins = (int) (zoneOff % 60L);
if (zoneMins < 0)
zoneMins = -zoneMins;
return (format.format(new Object[] { cal.getTime(), new Integer(zoneHrs), new Integer(zoneMins) }));
}

Categories