Stop date dropping zero's - java

How do I stop the ints dropping the zeros in the time? I've tried formatting it with
String.format("%02d", minutes);
but it doesn't work, I'm sure it's quite simple!
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
String curTime = hours + ":" + minutes;
String.format("%02d", minutes);
updatedat.setText("Updated at " + curTime);

Use a SimpleDateFormat object instead to format dates/times.
Date date = new Date(); // initializes to current time
DateFormat df = new SimpleDateFormat("h:mm");
updatedat.setText("Updated at " + df.format(date));
Read more about SimpleDateFormat and the formatting specifications here.

The reason it's not working is because String.format("%02d", minutes); is a function that returns a string
for your case if minutes was 8, String.format("%02d", minutes); would return 08
So, for this to work you'd have to have something like:
String curTime = hours + ":" + String.format("%02d", minutes);
I also agree that you shouldn't be formatting the time like this, use a date formatter.

One simple way of including 0's is to use a function like:
public String TwoCh(int i) { String s= "0" + Integer.toString(i); return s.substring(s.length() - 2); }
and then (notwithstanding the fact that getHours and getMinutes are both deprecated), you can do things like
String curTime = TwoCh(dt.getHours())+ ":" + TwoCh(dt.getMinutes());

I think what you want to do is to get the time in following format
22:01
In order to do that, use simpleDateFormat
you can read the full documentation, visit http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Related

GetTime doesn't correctly display zero's

I use TimeStamps in my system. Everything works correctly, however I find it annoying to have [12:2:2] as TimeStamp. Because you don't know if it's 20 or 2.
I am tired and sick, and starting to think it is the compiler.
java.util.Date date= new java.util.Date();
Timestamp time = new Timestamp(date.getTime());
super.print("[" + time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds() + "] ");re
How do you guys get correct TimeStamps with the zero's?
Have a look at the DateFormat or SimpleDateFormat class.
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
df.format(new Date());
Use simple String.format with %2d flag, i.e. decimal number with at least 2 digits.
String.format("[%2d:%2d:%2d] ", time.getHours(), time.getMinutes(), time.getSeconds())
You can use the DateTimeFormatter like this:
DateTimeFormatter format = DateTimeFormat.forPattern("HH:mm:ss");
DateTime dateTime = format.parseDateTime(s);
where s is your datatime string.

Get current date + 1 day for FQL query [duplicate]

This question already has answers here:
How to add one day to a date? [duplicate]
(18 answers)
Closed 9 years ago.
I need the get the current date like "yyyy-mm-dd" so not the hours and minutes.
And I need the current day 24hours futher so 1 day futher.
I need it in my fql query this is my query:
String FQL + = .... AND start_time<'" + startTime + "' AND start_time>'" + endTime + "' LIMIT 25"
I'm doing this with this code but it doesn't work:
Date myDate = new Date();
Date endTime = new Date(myDate.getTime() + 86400000L);
Date startTime = new Date(myDate.getTime());
When startTime < endTime
because
Date startTime = new Date(myDate.getTime());
Date endTime = new Date(myDate.getTime() + 86400000L);
how can the expression
X<'" + startTime + "' AND X>'" + endTime + "'
ever by true?
X < startTime X > endTime
---------------------------+---------------------+--------------------------
startTime endTime
I replaced it with X to better distinguish between start_time and startTime
Use java.util.Calendar
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 1); // adds 1 day
calendar.getTime(); // returns the Date
Good Luck!
Use a Calendar instance.
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat("yyy-MM-dd");
String startTime = sf.format(calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, 1);
String endTime = sf.format(calendar.getTime());
As Rene rightly points out, start_time needs to be GREATER than startTime (start_time > startTime) and SMALLER than your endTime (start_time < endTime).
Let me also point you to joda-time, which makes handling of dates much more comfortable. But for your purpose, the code above is just fine.
edit:
I read it as if the question was only about the format, but what René Link pointed out is right: Your query can never yield any results.
With java.util.Date it's something like:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
long now = System.currentTimeMillis();
Date today = new Date(now);
Date tomorrow = new Date(now + 86400000); // 24 * 60 * 60 * 1000
System.out.println("Today: " + dateFormat.format(today) +
"\nTomorrow: " + dateFormat.format(tomorrow));
With java.sql.Date it becomes slightly simpler:
long now = System.currentTimeMillis();
Date today = new Date(now);
Date tomorrow = new Date(now + 86400000);
System.out.println("Today: " + today + "\nTomorrow: " + tomorrow);
And maybe you might want to use java.util.Calendar.getInstance().getTime() instead of the System.currentTimeMillis() to create the first date. You then simply have to get the first date's time in millis to add the 86400000 to the second date.

Set date of calendar

Ok, so what I'm trying to do is to set the set the date of a calendar instance, and then return the week_of_year. I am doing so by using the Calendar.set() functio
public String weekInYearForm = "ww";
SimpleDateFormat formWIM = new SimpleDateFormat(weekInYearForm, Locale.US);
Calendar lc = Calendar.getInstance();
lc.set(Calendar.YEAR, lYear);
lc.set(Calendar.MONTH, lMonth);
lc.set(Calendar.DAY_OF_MONTH, lDay);
wiy = formWIM.format(lc.get(Calendar.WEEK_OF_YEAR));
To get the lYear, lMonth, and lDay values, I am passing a string in the format 04/26/2013 to through the following steps:
String[] arrDate = dateIn.split("/");
int lMonth = Integer.parseInt(arrDate[0]) - 1;
Log.d("SaveHandler", "Month is: " + lMonth);
int lDay = Integer.parseInt(arrDate[1]);
Log.d("SaveHandler", "Day is: " + lDay);
int lYear = Integer.parseInt(arrDate[2]);
Log.d("SaveHandler", "Year is: " + lYear);
The problem I am facing is that when I look at what is outputed to wiy, it is always 1. Upon some further debugging, I realized that the time is being left at epoch time, and not setting to the values I need.
I also tried using lc.set(lYear, lMonth, lDay), also to no avail. If anyone has any ideas, I would greatly appreciate them.
*EDIT: I did some debugging earlier and it is returning 1970 for the year and 0 for the month.
use
formWIM.format(lc.getTime());
instead of
formWIM.format(lc.get(Calendar.WEEK_OF_YEAR));
EDIT
You can parse your date (instead of dateIn.split( etc.)
SimpleDateFormat monthDayYear = new SimpleDateFormat("MM/dd/yyyy", Locale.US); //04/26/2013
Date date = monthDayYear.parse("04/26/2013");
and then format it
SimpleDateFormat formWIM = new SimpleDateFormat("ww", Locale.US);
formWIM.format(date);
This code is correct, the problem is in formWIM.format(...) or the battery of your motherboard clock is drained.

split String without delimiters

My controller recieves this String "20120115Z" as a #RequestParam, representing a date.
I would like to transform it to this format: yyyy-MM-dd, so I would have a new string like this 2012-01-15.
As you can see, there's no delimiters, only the 'Z' always as the last character.
My approach was pretty obvious:
String data =
strData.substring(0, 4) + "-" +
strData.substring(4, 6) + "-" +
strData.substring(6, 8);
And it works, but as you know these "magic numbers" are something to avoid. I also tried to use a a regular expression like "^[^\s]{4}[^\s]{2}[^\s]{2}Z$", but without success.
Any idea?
UPDATE: Finally I've done it with Joda-Time DateTime class as #Brian Agnew suggested
DateTimeFormatter fmt = DateTimeFormat.forPattern("YYYYMMdd'T'hhmm'Z'");
String strData = "20120115T0600Z";
DateTime dt = fmt.parseDateTime(strData);
printing method:
private static void printDateTime(DateTime dt) {
int year = dt.getYear();
int month = dt.getMonthOfYear();
int day = dt.getDayOfMonth();
int hour = dt.getHourOfDay();
int minute = dt.getMinuteOfHour();
int second = dt.getSecondOfMinute();
int millis = dt.getMillisOfSecond();
String zone = dt.getZone().toString();
log.info("fecha: "
+ day + "/" + month + "/" + year + " " + hour + ":" + minute + ":" + second + ":" + millis
+ " " + zone + "\n");
}
Output
15/1/2012 6:0:0:0 UTC
Thanks everyone
I would perhaps use a Joda-Time DateTimeFormat.
Why ? It'll check the format, including valid values for hours/minutes/seconds, and give you back a suitable DateTime object which you can do what with (including reformat it using a similar approach).
You simply give it the format that you want to parse and it'll do all the rest. You have a date, so treat it as such.

Time Duration problem

I am not able to get the correct Time duration.So can anyone please help me in finding the solution
//code
public static String getDateDifference(java.util.Date start, java.util.Date end) {
logger.info("Enter getDateDifference ");
Calendar startCal = Calendar.getInstance();
startCal.setTime(start);
Calendar endCal = Calendar.getInstance();
endCal.setTime(end);
int hourDiff = Math.abs(endCal.get(Calendar.HOUR_OF_DAY) - startCal.get(Calendar.HOUR_OF_DAY));
int minDiff = Math.abs(endCal.get(Calendar.MINUTE) - startCal.get(Calendar.MINUTE));
String diff = Integer.toString(hourDiff) + ":" + Integer.toString(minDiff);
logger.info("Date Difference : " + diff);
logger.info("Exit getDateDifference ");
return diff;
}
Won't this fail if the start is 23:59 and the end 00:01?
Instead just get the milliseconds from the two dates, subtract and then convert to hours and minutes.
long millis = end.getTime() - start.getTime();
long seconds = millis/1000L;
long hours = seconds/3600L;
long mins = (seconds % 3600L) / 60L;
If you can use JodaTime this becomes fairly trivial. Like so:
Period period = new Period( new DateTime( start ), new DateTime( end ), PeriodType.time() );
return period.getHours() + ":" + period.getMinutes();
why don't you do the following
1) convert your 2 Dates to a common unit (here hours)
2) calculate the difference
3) transform the result to a format you want (Date, string ...)
I don't have the code handy but it should be fairly straight forwards.
your method is open to small errors like forgetting to increment/decrement a day when you go above 24h or under 0h.
also it will be diffcult to maintain if you want to suddenly add minutes and seconds ...
hope this helps
Jason

Categories

Resources