How to make a string in java understand current local time - java

Here's my code, I'm trying to my 'calculateButton' variable to understand the current local time so that it can use it in the math equation. Thanks for taking a look. By the current time, I mean the time currently being shown on my computer or the time zone I'm in.
private void bednowButtonActionPerformed(java.awt.event.ActionEvent evt) {
//variable declaration
String calculateButton, outputTime;
double outputtimeConstant;
calculateButton= "";
//math
outputtimeConstant = +104;
outputTime = calculateButton + outputtimeConstant;
//output
bednowOutput.setText(outputTime) ;
}

To get the current date and time just use static method now() of LocalDateTime or ZonedDateTime classes (you mentioned time zone here, so I'm specifying this implementation as well). For some math with these objects afterwards just use their instance methods, like plusDays, plusHours... and so on. I'd recommend reading documentation of these classes, they are quite useful.
If you want to have a String representation simply call toString() method.

Related

How to compare TimeZones

I need to compare time zones such that Asia/Singapore < UTC < Pacific/Honolulu.
I'm working with java.util.TimeZone (which doesn't implement Comparable).
My search for an existing implementation was unsuccessful because of the overwhelming number of questions about comparing dates with different time zones.
Question: What is a correct implementation of Comparator<TimeZone> that will solve this problem (and what makes it better than other solutions, if applicable)?
Note that I'm not able to use Joda Time for this problem, so "use Joda Time" is not a valid answer.
Edit for clarity
The < notation above was not well defined. My particular use case only requires a naive "geographical" ordering from east to west. As the comments have pointed out, a more advanced and generalizable solution would take into account temporal factors like daylight savings time and historical GMT offset changes. So I think there are two orderings we can consider, each requiring a different Comparator<TimeZone> implementation:
Strictly geographical (current UTC) - addressed by my answer.
Sensitive to local or civil time changes - addressed by rgettman's answer.
I rolled my own Comparator<TimeZone> implementation using getRawOffset for the comparison:
#Override
public int compare(TimeZone tz1, TimeZone tz2) {
return tz2.getRawOffset() - tz1.getRawOffset();
}
It seems to have passed a quick test:
final List<TimeZone> timeZones = Arrays.asList(
TimeZone.getTimeZone("UTC"),
TimeZone.getTimeZone("America/Los_Angeles"),
TimeZone.getTimeZone("America/New_York"),
TimeZone.getTimeZone("Pacific/Honolulu"),
TimeZone.getTimeZone("Asia/Singapore")
);
final List<TimeZone> expectedOrder = Arrays.asList(
TimeZone.getTimeZone("Asia/Singapore"),
TimeZone.getTimeZone("UTC"),
TimeZone.getTimeZone("America/New_York"),
TimeZone.getTimeZone("America/Los_Angeles"),
TimeZone.getTimeZone("Pacific/Honolulu")
);
Collections.sort(timeZones, new Comparator<TimeZone>() {
#Override
public int compare(TimeZone tz1, TimeZone tz2) {
return tz2.getRawOffset() - tz1.getRawOffset();
}
});
//Impl note: see AbstractList.equals
System.out.println(timeZones.equals(expectedOrder)); //true
But I'm still wondering whether there are pitfalls to this solution and/or if there's something preferable.
One might be able to create a Comparator<TimeZone> that takes into account time zone differences. The TimeZone may or may not obvserve daylight savings time, which would adjust the raw offset, thus messing up raw-offset-only comparisons. The TimeZone class seems to support the adjustment based on the 2 getOffset methods, but they need a reference date. How about:
public class TimeZoneComparator implements Comparator<TimeZone>
{
private long date;
public TimeZoneComparator(long date)
{
this.date = date;
}
public int compare(TimeZone tz1, TimeZone tz2)
{
return tz2.getOffset(this.date) - tz2.getOffset(this.date);
}
}
Timezones are purely political, so any use of them that is non-conforming will cause LOTS of problems for users, depending on what the app does and who needs it or uses it. You question would be better asked by explaining why you need them ordered like that. There are adjacent timezones where one uses DST the other does not. So 60% of the year, the TZ1 == TZ2, the other 40% TZ1 < TZ2. Or whatever the case may be.
There are geographic (lat long) timezone data sets, and web sites to query for timezone. Even current DST settings. So you may have to settle for a data set that you need to update frequently at least yearly. Or web access.
You probably should not assign magnitude to them. Only geographic ordering - by longitude.
First of if you could tell us what you are trying to do it'd be great. And the answer is not: strict a>b>c order based on local time. I coded calendrics for a while, so I actually used to know this stuff.
What explictly do believe requires this kind of ordering?

How can I assign an int to a String variable?

I am currently making an assignment for Java but I am stuck. I have to make a birthdate from the three parameters: day, month and year, which are numbers = int. With this I have to put in some checks for valid dates. That part I think is done, but I get stuck at the following:
I want an if statement to check the day, and if the day is correct, this block of code should be run trough
if (dag >=1 && dag <=31)
{
datum = dag;
}
datum Is a String, because I want to get the date like this: DD-MM-YYY
And dag is an Int. So whenever I try to compile this, BlueJ gives an error at this part saying "incompatible types". I assume this is because I try to place a Int in a String. Is this possible in any way, because I can't find out how.
Use String.valueOf method to convert int to string: -
int i = 32;
String str = String.valueOf(i);
And of course follow the advice in #Brian's answer as to what you should rather do in your case.
Don't make it a string. it's not. I think you should
create a Date object to represent your date (day/month/year combined)
use SimpleDateFormat to print that date out in the appropriate format
That's the proper OO way to do it. Otherwise you end up with a bunch of disparate disconnected variables representing in their combination some object type, but you can't manipulate them atomically, invoke methods on them etc. Holding everything as strings is known as stringly-typing (as opposed to strongly-typing) and is a particularly bad code smell!
At some stage check out Joda-Time for a better date/time API than those suggested above. However for the moment I suspect you've got enough on your plate without downloading extra jars.

Java Compare dates to check if in range

ok not as simple as title may make it sound. I tried this in a very primal way with c# and it worked, but I have a feeling a better job could be achieved with Java and Oracle as database. So the thing is:
I have a reservation system. multiple bookings could be made on the same day for period between date X and date Y as long as each day in the range can accommodate the requested number. Maximum number of clusters to reserve is 46. Hence logically you would look at each day as a holder of 46 cluster reservation and deduce from that.
Now what I have difficulty working out is:
when there are n number of bookings stored and valid in database, then I want to make new booking. So how do I check if this new date range falls within any of the previously booked days or not. Not talking simply here about x falling in y (as ranges). More like:
X_______________________________________Y
X________________________________y
X________________________________Y
X________________________________Y
as u can see the overlap is happening.
Please let me know how could I do this as it will affect early design of objects
Regards
Assume your date has two methods: isBefore(Date other) and isAfter(Date other). Obviously if they don't you can cure this with an external method or wrapping or something. Edit: java.util.Date has compareTo method you could use.
You do this:
public boolean overlapsWithExisting(Booking booking) {
final Date early = booking.getStart();
final Date late = booking.getEnd();
for(Booking existing : existingBookings) {
if(!(early.isAfter(existing.getEnd()) || late.isBefore(existing.getStart()))
return true;
}
return false;
}
We compare this booking to all existing bookings. If this booking ends before the existing booking even starts, or if this booking starts after the existing booking ends, then it doesn't conflict. Any other condition and they will overlap.
Do this to each booking.
Joda-Time – Interval
Rather than roll your own, use the Interval class in the Joda-Time library. An Interval is a pair of specific points along the timeline, each defined as a DateTime instance.
The Interval class offers overlap, gap, and abuts methods.
Half-Open
Those methods wisely use the Half-Open approach to spans of time where the beginning is inclusive while the ending is exclusive. Search StackOverflow for more info.

java get duration from database

table structure:
sysdurationtimeday , sysdurationtimehour, sysdurationtimeminute
1, 12,10
3, 23,10
0, 0,10
i have these 3 fields from database, after getting these 3 values, what is the technique that i can use do cast to which Java Object? (maybe Calendar.class, TimeStamp.class) ?
and use it to compared with record is spent less than 1 day, more than 1 day + less than 3 days. etc?
As long as you're talking durations and not absolute times, this is pretty easy. Just express the time in a convenient unit, say seconds:
time_in_seconds = 86400*sysdurationtimeday +
3600*sysdurationtimehour +
60*sysdurationtimeminute
In Java the standard way to represent this is actually as a long value in milliseconds, ala System.currentTimeMillis().
All the standard Java classes are intended to handle absolute times and need to deal with daylight savings, leap years, and all that crap. At least with the data you gave us, you don't have the required info anyway: there's no way to tell if the day was a daylight savings day and therefore took 23 or 25 hours instead of 24.
I would prefer my own class, overriding the "essential" methods.
public class SysDuration implements Comparable {
int day;
int hour;
int min;
public SysDuration(int day,int hour,int min) {
}
public boolean equals(Object obj) {
}
public int hashCode() {
}
public int compareTo(Object obj) {
}
public boolean spendLess(SysDuration dur) {
}
}
Lots of good answers already.
A sugegstion, perhaps out of scope, if you use durations in java I would prefer to
just calculate and store this in one variable, typically a long in milliseconds
if this resolution is good enough. The splitting in 3 variables usually
make most of the code more complicated.
Calculations are easier and intergartion with libs such as jodatime and similar will be
even more simple.
If you literally want "more than 1 day", that is there's no rounding so d=1, h=23, m=59 gives you 1 day, not 2 days then you can just use sysdurationtimeday and completely ignore hours and minutes. (That assumes you don't have more than 24 in sysdurationtimehour).
Classes such as Calendar don't help, they are for manipulating actual dates, you already are working in durations.
Jodatime supports durations and then you get the operations needed for free.
If you are hesitant to add another dependency and learning curve, I would create a little custom class with a field storing the duration as a number in the desired precision. Then add some methods to do your comparisons or return a Calendar object or a Date aded and subtracted with your duration.
My guess is this will end up being cleaner than using the standard Java API's which always end up in complicated, clunky code when you start manipulating time.

Getting a nicely formatted timestamp without lots of overhead?

In my app I have a textView which contains real-time messages from my app, as things happen, messages get printed to this text box. Each message is time-stamped with HH:MM:SS.
Up to now, I had also been chasing what seemed to be a memory leak, but as it turns out, it's just my time-stamp formatting method (see below), It apparently produces thousands of objects that later get gc'd. For 1-10 messages per second, I was seeing 500k-2MB of garbage collected every second by the GC while this method was in place. After removing it, no more garbage problem (its back to a nice interval of about 30 seconds, and only a few k of junk typically)
So I'm looking for a new, more lightweight method for producing a HH:MM:SS timestamp string :)
Old code:
/**
* Returns a string containing the current time stamp.
* #return - a string.
*/
public static String currentTimeStamp() {
String ret = "";
Date d = new Date();
SimpleDateFormat timeStampFormatter = new SimpleDateFormat("hh:mm:ss");
ret = timeStampFormatter.format(d);
return ret;
}
Make your SimpleDateFormat be static final, rather than creating one each time.

Categories