I have to use java.util.Calendar in GWT entry point, but I got error while running the application, that is because GWT is not able to find source code, is there anyway I could fix this issue.
Thanks in advance!!!
java.util.Calendar is not an emulated class. You can find a list of emulated classes here:
http://code.google.com/webtoolkit/doc/latest/RefJreEmulation.html
I would strongly advise not to use any date/calendar library on the client side. You will probably only get yourself into trouble. In fact, even though java.sql.Date and java.util.Date are emulated in GWT, I would not use these either. If you're looking to use Calendar, then chances are you want to support timezones on the client. Using the emulated Date classes, you will somehow have to convert the client's Date from the browser's timezone to some target timezone (GMT or whatever the user defined in user preferences?). This will most definitely be error prone. Using GWT's TimeZone adds other issues. For instance, how do you map between java TimeZones and GWT TimeZones?
I recommend doing all date manipulation AND formatting on the server. On the client, you can simply use a date/month/year triplet. The server can have an association between user (or organization) and java.util.TimeZone (or joda timezone). Using the triplet and timezone you can easily create the specific instance in time.
You may be able to use com.google.gwt.user.datepicker.client.CalendarUtil.
No there is no way to use the java.util.Calendar in GWT because there is no equivalent in JavaScript. But there is an accepted feature request for it. Maybe you will find some hints in the comments of the request.
The following shows how to use Joda Time to extract any date information from a Java Date type with Joda Times format() function and use it to build a new Date() using Joda Time's parse() function.
static DateTimeFormat dtf = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss.SSS");
static DateTimeFormat datefmt = DateTimeFormat.getFormat("yyyy-MM-dd ");
static DateTimeFormat timefmt = DateTimeFormat.getFormat("HH:mm:ss.SSS");
public Date getDateTime(Date date, Date time) {
String datetime = datefmt.format(date) + timefmt.format(time);
return dtf.parse(datetime);
}
Have you tried adding actual code of the class to your project? Some Java SDK classes compile well even though they are not in JRE white list.
For those who prefer implementing the math directly, here is a solution for how to add days to an existing date object without using Calendar or any deprecated functions:
private Date addDays(Date dateIn, int numDays)
{
long milisPerDay = 86400000;
// convert the dateIn to milliseconds
long dateInMilis = dateIn.getTime();
// add numDays to the date
dateInMilis = dateInMilis + (numDays * milisPerDay);
return new Date(dateInMilis);
}
Here's how to get the current year as a String (very useful for Copyright notices)
long time = System.currentTimeMillis();
long milisPerYear = new BigInteger("31536000000").longValue();
String currentYear = String.valueOf((int) Math.floor(time / milisPerYear) + 1970);
Finding the constants such as number of miliseconds in a day, year, etc. is easy with Google. The tricky part is adding months, since the number of milliseconds in a month is going to depend on the month. If there's any demand for it, I'd be happy to write a function and post it here in order to add and subtract months.
Related
I would like to use a Date field in my playOrm mapping. However, if I use
private Date birthDate;
in my bean, it gives me an exception saying this type is not supported.
I can add Date if you open an issue. I was thinking of actually throwing an exception when people use Date that says this though instead..
Please use LocalDate, LocalTime or LocalDateTime from joda-time which
was supposed to be added in jdk7 but more than likely will end up in
jdk8. The reason for this is java.util.Date and Calendar from java
are buggy and have lots of known bugs in the jdk bug system.
See this as well
Joda Time to be included in Java 7?
If however, you still want to use Date, here is how
Map<Class, Converter> converters = new HashMap<Class, Converter>();
Converter d = new DateConverter();
converters.put(Date.class, d);
Then you need to implement the Converter interface with your DateConverter class and implement the byte[] to Date and Date to byte[] and String to Date and Date to String methods. NOTE: These methods are all called for S-SQL and for converting entities...it all uses the same converters.
The string conversions are VERY important as the command line tool will use them to convert your command line S-SQL to query the objects.
HOWEVER, if you want it built-in to PlayOrm, just open an issue and I can do it pretty quickly BUT I still suggest you use LocalDateTime instead in joda-time as it is more reliable and you can do more with it....after using joda-time quite a bit, it is on-par with C# date apis and way better than the old java stuff.
Dean
I'm not sure what you're asking for, but as stated in the Java API for Date, "As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated."
i build a new website.but the host is in USA.i am not in USA.
i need get the time on the website page to compare with one local Variable.
But because of time difference,it has 8 hous difference。how to solve this problom?
my code
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
java.util.Date currentTime = new java.util.Date();
String dateString = formatter.format(currentTime); `
how to revise these code ?
java.util.Date does not support timezones. You should pass the TimeZone to the formatter instead, by calling formatter.setTimeZone(tz).
joda-time is considered a better choice when working with dates. Note that for the sake of formatting it is fine to use Date, but it is a general advise not to rely on it when it comes to i18n. (Note the many deprecated methods there)
Then make each user set his timezone. Ideally suggest / assume the timezone based on his browser locale. See here
And always store the dates in a fixed timezone - preferably GMT/UTC.
In order to handle timezones, Java includes the Olson timezone database. Find the city in the database that is in the same time zone as you are.
First, you need to get a TimeZone object for the timezone you want. Then, get a Calendar object with the current date and time (or the date and time you wish to use). You can format that with a SimpleDateFormat object.
TimeZone local = TimeZone.getTimeZone("Asia/Tokyo");
Calendar now = Calendar.getInstance(local); // gets time in the current timezone
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
formatter.setTimeZone(local)
String dateString = formatter.format(now.getTime());
Though if you're doing a lot of time manipulation, like Bozho says, go for joda-time. The Java date/time system is confusing and rather poorly designed.
In such cases I always change timezone in Linux:
mv /etc/localtime /etc/localtime-backup
ln -sf /usr/share/zoneinfo/Europe/Amsterdam /etc/localtime
It also can be helpful for reading log files for example (I always see my local time instead of calculating it each time when I need to dig into them)
I think you need to use a Calendar (they are more useful generally than just Date objects). If you create a Calendar, initialised with your locale and timezone, you can do calendar.setDate() using the date you created. If you create another Calendar object with the fields that were entered, you can then do comparisons between the two Calendar objects.
Eclipse is warning that I'm using a deprecated method:
eventDay = event.getEvent_s_date().getDate();
So I rewrote it as
eventDay = DateUtil.toCalendar(event.getEvent_s_date()).get(Calendar.DATE);
It seems to work but it looks ugly. My question is did I refactor this the best way? If not, how would you refactor? I need the day number of a date stored in a bean.
I ended up adding a method in my DateUtils to clean it up
eventDay = DateUtil.getIntDate(event.getEvent_s_date());
public static int getIntDate(Date date) {
return DateUtil.toCalendar(date).get(Calendar.DATE);
}
It's fine. To me the uglier bit is the underscore in the method name. Java conventions frown upon underscores there.
You may want to take a look at joda-time. It is the de-facto standard for working with date/time:
new DateTime(date).getDayOfMonth();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Integer date = cal.get(Calendar.DATE);
/*Similarly you can get whatever value you want by passing value in cal.get()
ex DAY_OF_MONTH
DAY_OF_WEEK
HOUR_OF_DAY
etc etc..
*/
You can see java.util.Calendar API.
With Java 8 and later, it is pretty easy. There is LocalDate class, which has getDayOfMonth() method:
LocalDate date = now();
int dayOfMonth = date.getDayOfMonth();
With the java.time classes you do not need those third party libraries anymore. I would recommend reading about LocalDate and LocalDateTime.
If you want a more elegant Date/Time api, use Joda Time.
I'm trying to do something really simple, but starting to realize that dates in Java are a bit of minefield. All I want is to get passed groups of three ints ( a year, a month and a date) create some Date objects, do some simple test on them (along the lines of as date A before date B and after January 1 1990), convert them to java.sql.Date objects and pass them off to the database via JDBC.
All very simple and works fine using the java.util.Date(int year,int month,int day) constructor. Of course that constructor is depreciated, and I'd like to avoid using depreciated calls in new code I'm writing. However all the other options to solve this simple problem seem stupidly complicated. Is there really no simple way to do what I want without using depreciated constructors?
I know the standard answer to all Java date related questions is "use joda time", but I really don't want to start pulling in third party libraries for such a seemingly trivial problem.
The idea is to use the Calendar class, like so:
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
Date date = cal.getTime();
Indeed, if you check the Javadoc of the constructor you are mentioning, it is exactly what is suggested:
Date(int year, int month, int date)
Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
Or ... use JodaTime :-).
Well, you can use the deprecated constructor. It has been deprecated for over 13 years and still works - it isn't going anywhere. If you don't want to do that and don't want to use a third party library, you have to use Calendar.
In Java 7, hopefully there will be a new time API, and you won't have the need for a third party API anymore.
LG's answer is valid but in general you should use Calendar for all your date operations and leave Date out of it unless your API requires it explicitly. In that case you can just convert it when passing it to the API.
How do I formate a java.sql Timestamp to my liking ? ( to a string, for display purposes)
java.sql.Timestamp extends java.util.Date. You can do:
String s = new SimpleDateFormat("MM/dd/yyyy").format(myTimestamp);
Or to also include time:
String s = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(myTimestamp);
Use String.format (or java.util.Formatter):
Timestamp timestamp = ...
String.format("%1$TD %1$TT", timestamp)
EDIT:
please see the documentation of Formatter to know what TD and TT means: click on java.util.Formatter
The first 'T' stands for:
't', 'T' date/time Prefix for date and time conversion characters.
and the character following that 'T':
'T' Time formatted for the 24-hour clock as "%tH:%tM:%tS".
'D' Date formatted as "%tm/%td/%ty".
If you're using MySQL and want the database itself to perform the conversion, use this:
DATE_FORMAT(date,format)
If you prefer to format using Java, use this:
java.text.SimpleDateFormat
SimpleDateFormat dateFormat = new SimpleDateFormat("M/dd/yyyy");
dateFormat.format( new Date() );
For this particular question, the standard suggestion of java.text.SimpleDateFormat works, but has the unfortunate side effect that SimpleDateFormat is not thread-safe and can be the source of particularly nasty problems since it'll corrupt your output in multi-threaded scenarios, and you won't get any exceptions!
I would strongly recommend looking at Joda for anything like this. Why ? It's a much richer and more intuitive time/date library for Java than the current library (and the basis of the up-and-coming new standard Java date/time library, so you'll be learning a soon-to-be-standard API).
Use a DateFormat. In an internationalized application, use the format provide by getInstance. If you want to explicitly control the format, create a new SimpleDateFormat yourself.
java.time
I am providing the modern answer. The Timestamp class is a hack on top of the already poorly designed java.util.Date class and is long outdated. I am assuming, though, that you are getting a Timestamp from a legacy API that you cannot afford to upgrade to java.time just now. When you do that, convert it to a modern Instant and do further processing from there.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
.withLocale(Locale.GERMAN);
Timestamp oldfashionedTimestamp = new Timestamp(1_567_890_123_456L);
ZonedDateTime dateTime = oldfashionedTimestamp.toInstant()
.atZone(ZoneId.systemDefault());
String desiredFormat = dateTime.format(formatter);
System.out.println(desiredFormat);
Output in my time zone:
07.09.2019 23:02:03
Pick how long or short of a format you want by specifying FormatStyle.SHORT, .MEDIUM, .LONG or .FULL. Pick your own locale where I put Locale.GERMAN. And pick your desired time zone, for example ZoneId.of("Europe/Oslo"). A Timestamp is a point in time without time zone, so we need a time zone to be able to convert it into year, month, day, hour, minute, etc. If your Timestamp comes from a database value of type timestamp without time zone (generally not recommended, but unfortunately often seen), ZoneId.systemDefault() is likely to give you the correct result. Another and slightly simpler option in this case is instead to convert to a LocalDateTime using oldfashionedTimestamp.toLocalDateTime() and then format the LocalDateTime in the same way as I did with the ZonedDateTime.
String timeFrSSHStr = timeFrSSH.toString();