I basically want to say
if the date is unchanged run this alert
my date field is set up like this
StartDate = new DateField("Start Date ", DateField.DATE);
cal1 = Calendar.getInstance();
cal1.set(Calendar.YEAR, 2009);
cal1.set(Calendar.MONTH, 3);
cal1.set(Calendar.DAY_OF_MONTH, 1);
StartDate.setDate(cal1.getTime());
and i have this but i am not sure where to begin to make it right.
if(StartDate.equals(Calendar.DAY_OF_MONTH, 1))
{
AlertNameNotEntered.setString("Please select a Start Date");
mDisplay.setCurrent(AlertNameNotEntered);
}
Thanks
I assume you want something like this:
if(StartDate.getDate().getTime() == cal1.getTime()) // Date is unchanged
{
AlertNameNotEntered.setString("Please select a Start Date");
mDisplay.setCurrent(AlertNameNotEntered);
}
It seems to me you have quite a few gaps in your knowledge regarding basic Java. There are no short-cuts to getting to know the language and the standard library. Consult javadocs for Calendar, Date and DateField classes.
Related
I'm having a problem and I absolutely can't wrap my head around it. I am inexperienced in Java (or any language, for that matter), so excuse me if this is a stupid question.
From what I can tell, the format() method from java.time.format.DateTimeFormatter is not working how I thought it did. I am consistently getting the following error message (CLI):
Watch.java:609: error: cannot find symbol
String dateTimeDisplay = dateTime.format(dateTimeFormat);
^
symbol: method format(DateTimeFormatter)
location: variable dateTime of type Object
1 error
And here are the bits of code I think are relevant:
import java.time.ZonedDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class Watch {
protected int hour, hourTens, hourOnes, minute, minuteTens, minuteOnes, amPM;
public void watchMethod(String userInput) {
Object dateTime; // Create reference to object called dateTime
switch (userInput) {
case "1":
ZonedDateTime dateTimeHere = ZonedDateTime.now();
hour = dateTimeHere.getHour();
minute = dateTimeHere.getMinute();
// amPM is used exclusively to display AM/PM or a heart (see lines 580 to 567).
amPM = dateTimeHere.getHour();
dateTime = dateTimeHere;
break;
case "2":
ZonedDateTime dateTimeThere = ZonedDateTime.now(ZoneId.of("Europe/Paris"));
hour = dateTimeThere.getHour();
minute = dateTimeThere.getMinute();
// amPM is used exclusively to display AM/PM or a heart (see lines 560 to 567).
amPM = dateTimeThere.getHour();
dateTime = dateTimeThere;
break;
case "3":
hour = -1;
minute = -1;
break;
}
// There is some code that prints things to console depending on the hour, minute, and amPM variables.
// I don't think this is relevant, but that's what's here.
// The following code prints out the actual date and time from a ZonedDateTime object.
DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("hh:mm a 'on' EEEE, MMMM dd, yyyy");
String dateTimeDisplay = dateTime.format(dateTimeFormat); // ERROR
System.out.print("\nIt is currently " + dateTimeDisplay + "\n");
}
}
This is all one class.
I have checked that my imports are correct and that there are no misspellings anywhere! This is what other questions related to my problem have led me to believe was the issue, but it doesn't seem to be the case.
I'm also not very familiar with using Object as a reference type, so if that could be what's causing the problem, I'm not surprised. It's all I could figure out to break dateTimeHere/dateTimeThere out of the switch block.
Anyway, I'd greatly appreciate any help I receive.
QUICK EDIT: I also figured that if there were no suitable dateTime object (i.e. case "3"), this would also cause an error. I briefly added an if/else statement to remedy this, with some code in case "3" indicating that dateTime was null, but this did absolutely nothing. Let me know if I should re-add this, though.
EDIT: Thanks to a comment from #MarsAtomic, I see that this post could have used another read-through. My problem is that at the end of my code, I want to print out the ZonedDateTime data the switch statement retrieved, whether that is from the user's computer location or "Paris/Europe". Eventually, that "Paris/Europe" string will (ideally) have some user input from a subclass (as is the case with userInput, but that particular string was just for choosing one of the 3 cases already shown).
You probably meant to declare dateTime as a ZonedDateTime, as Object's definition does not include a format method.
Revised code:
ZonedDateTime dateTime = null; // Create reference to object called dateTime
//...
DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("hh:mm a 'on' EEEE, MMMM dd, yyyy");
if (dateTime != null) {
String dateTimeDisplay = dateTime.format(dateTimeFormat);
System.out.print("\nIt is currently " + dateTimeDisplay + "\n");
}
Hi there how to show allow ui date picker for time field using 24 hours format?
I'f I'm using
[code]
<%
Calendar dob = CalendarFactoryUtil.getCalendar();
dob.setTime(new Date());
%>
<aui:input name="schedule_msg" model="<%= Message_Schedule.class %>"
bean="<%= msch %>" value="<%= now %>" label="Schedule Time"/>
[/code]
it shows in am/PM mode...or if using AM/PM mode how to get the value??normally if i want to get value in my Portlet Class just like this
[code]
int day = ParamUtil.getInteger(request, "schedule_msgDay");
int month = ParamUtil.getInteger(request, "schedule_msgMonth");
int year = ParamUtil.getInteger(request, "schedule_msgYear");
int hour = ParamUtil.getInteger(request, "schedule_msgHour");
int min = ParamUtil.getInteger(request, "schedule_msgMinute");
try
{
msgSchedule.setSchedule_msg(PortalUtil.getDate(month, day, year, hour, min, new PortalException()));
}catch(Exception e)
{
msgSchedule.setSchedule_msg(new Date());
}
[/code]
any idea how to get that value??
example in the picture it show 4:54: PM so it means in 24 hours it become 16:54:00 .... Please any help
Thank's
Regards
Danial
The aui:input taglib (which in turn uses the liferay-ui:input-date and liferay-ui:input-time taglibs) shows the AM/PM select box if the time format for the current locale requires it. In Liferay 6.1.1, have a look at row 36 in html/taglib/ui/input_time/page.jsp.
So you should definitely keep the built-in behavior, which shows the AM/PM select box depending on the current locale.
In order to get the date properly in your portlet class, you can draw inspiration from the EditEventAction class, which is the Struts action called when you add, update or delete an event in the Calendar portlet. Something like this:
int startDateMonth = ParamUtil.getInteger(actionRequest, "startDateMonth");
int startDateDay = ParamUtil.getInteger(actionRequest, "startDateDay");
int startDateYear = ParamUtil.getInteger(actionRequest, "startDateYear");
int startDateHour = ParamUtil.getInteger(actionRequest, "startDateHour");
int startDateMinute = ParamUtil.getInteger(actionRequest, "startDateMinute");
int startDateAmPm = ParamUtil.getInteger(actionRequest, "startDateAmPm");
if (startDateAmPm == Calendar.PM) {
startDateHour += 12;
}
After that, if you want to get a Date object from these values, it's important to decide whether these values represent a date in UTC, in the current user's timezone or whatever. Have a look at the addEvent method in CalEventLocalServiceImpl class to know how to do it: basically, you have to create a Calendar object with the CalendarFactoryUtil.getCalendar method, passing a locale and a timezone, and then you can set the various values.
Liferay UI part is poorly documented, here is the attributes I found, http://docs.liferay.com/portal/6.2/taglibs/liferay-ui/input-time.html, but it never describe how to use these attributes, what are the values of these attributes.
I wasted too much time on googling and experimenting, and I decided to use JQuery datetime pick instead.
Another way is don't use liferay-ui:input-time, just to use your own hours and mins select input.
I am working on a project that will run many thousands of comparisons between dates to see if they are in the same month, and I am wondering what the most efficient way of doing it would be.
This isn't exactly what my code looks like, but here's the gist:
List<Date> dates = getABunchOfDates();
Calendar month = Calendar.getInstance();
for(int i = 0; i < numMonths; i++)
{
for(Date date : dates)
{
if(sameMonth(month, date)
.. doSomething
}
month.add(Calendar.MONTH, -1);
}
Creating a new Calendar object for every date seems like a pretty hefty overhead when this comparison will happen thousands of times, soI kind of want to cheat a bit and use the deprecated method Date.getMonth() and Date.getYear()
public static boolean sameMonth(Calendar month, Date date)
{
return month.get(Calendar.YEAR) == date.getYear() && month.get(Calendar.MONTH) == date.getMonth();
}
I'm pretty close to just using this method, since it seems to be the fastest, but is there a faster way? And is this a foolish way, since the Date methods are deprecated? Note: This project will always run with Java 7
I can't comment on whether to use the deprecated methods, but if you choose not to there's no need to instantiate a new Calendar for every Date you check. Just use one other Calendar and call setTime(date) before the check (or one Calendar for every thread if you parallelize it).
As a side note, I do have to agree with ChristopheD's comment that this is something worthy of a database.
I think you can define a static DateFormat to extract the month and year from Date and use both objects as date only.
public static DateFormat formatter= new SimpleDateForm("MMyyyy");
public static boolean sameMonth(Date date1, Date date2)
{
return formatter.format(date1).equals(formatter.format(date2));
}
Friends I am having a String that contains date-record
String date=10-Oct-2012 #12-Oct-2012 #$12-Oct-2012 #12-Oct-2012 #$12-Sept-2012 13:50#12-Oct-2012 13:50#$12-Feb-2012 13:50#12-Oct-2012 13:50#$
List<Date> myList=new ArrayList<Date>() ;
I need to compare the dates 10-Oct-2012,12-OCt-2012,12-Sept-2012,12-Feb-2012 ie every odd date such that I can arrange them in a chronological order.I am confused on this implementation, please provide me with guidance/hint to solve the problem.
In this case the solution after chronological order would be 12-Feb-2012 #12-Oct-2012 #12-Sept-2012 #12-Oct-2012 #$10-Oct-2012 #12-Oct-2012 #$12-Oct-2012 #12-Oct-2012
Friends,to solve the problem I have created a Hashmap where I am planning to save the first date as key and the entire String as value.
String[] tokens=date.split("\\$");
demo[0]=demo[0].replaceAll("-", ".");
if(tokens.length>0)
{
for(int iTmp=tokens.length-1;iTmp>=0;iTmp--)
{
String []demo = tokens[iTmp].split("\\#");
demo[0] = demo[0].replace("Jan", "1")
.replace("Feb", "2").replace("March","3").replace("April","4").replace("May","5").replace("Jun","6").replace("July","7").replace("Aug","8")
.replace("Sept","9").replace("Oct","10").replace("Nov","11").replace("Dec","12");
demo[0]=demo[0]+" 00:05:00";
Date date1 = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yy");
try {
date1 = (Date)formatter.parse(demo[0]);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myList.add(date1);
System.out.println("ADDED DATE IS"+date1);
//System.out.println("KEY VALUE PAIRS "+key+" "+tokens[iTmp]);
}
}
System.out.println("READING LISTs");
for(int iTmp=0;iTmp<myList.size();iTmp++)
{
System.out.println(myList.get(iTmp));
}
Collections.sort(myList);
System.out.println("After Sorting");
for(int iTmp=0;iTmp<myList.size();iTmp++)
{
System.out.println(myList.get(iTmp));
System.out.println();
}
It sounds pretty simple to me:
Parse each value into a more suitable type (Calendar, Date, Joda Time's LocalDate)
Sort in natural order
(Using Joda Time is the preferred option here IMO, as neither Calendar nor Date really represent "just a date"; you'd have to put all values into the same time zone etc.)
I would definitely not recommend trying to compare them as strings. As usual, convert your data into the most appropriate type for the information it's trying to represent as early as possible - and convert it into serializing representations (e.g. for storage, propagation to a web service etc) as late as possible.
Split the string and then
You can use gregorian calender (built in)
or you can use the yoda-time library
i can't say more about the sorting though
If you are developing for Android (there is an Android tag on your question), then you should know about the Time structures and methods in the Android SDK.
If possible, try to use a string representation of your date/time stamp that itself can be sorted naturally, like the RFC 3339 format (which Android supports with built-in methods). This will let you work more easily with string timestamps, and also give you a simple way to convert to a canonical or integer-type format if desired.
I have a list of objects called Activity:
class Activity {
public Date activityDate;
public double amount;
}
I want to iterate through List, group them by date and return a new list . Here's what I currently do:
private List<Activity> groupToList(List<Activity> activityList) {
SimpleDateFormatter sdf = new SimpleDateFormatter("YYYY-MM-DD");
Map<String,Activity> groupMap = new HashMap<String,Activity>();
for (Activity a in activityList) {
String key = sdf.format(a.getActivityDate());
Activity group = groupMap.get(key);
if (group == null) {
group = new Activity();
groupMap.add(key, group);
}
group.setAmount(group.getAmount() + a.getAmount());
}
return new ArrayList<Activity>(groupMap.values());
}
Is it a WTF to use the DateFormatter in this way?
I'm using the DateFormatter because each activityDate could have time information.
I would just use the date object itself as the key. If it it bothers you because the date object is mutable, then use its toString() value. No reason to go making formats.
If the issue is that you want to normalize the date by removing the time component, it would be much better to do that withing the Activity object and remove the time component. If the issue is still further that there are potential time zone issues, I would use JodaTime, but there is no object in the JDK currently that represents a pure date without time, so going with a string isn't outrageous, but it should be hidden behind a method in the Activity object and the fact that it is a date formatted string without a time component should be an implementation detail.
java.util.Date is a quite poor abstraction for your need; it is IMO fair to stick to strings if nothing better is around, HOWEVER Joda-time provides a good datatype for you: DateMidnight or alternatively LocalDate if Activity is strictly timezome-independant.
other than that, the code looks good to me, you might be able to shorten it a bit using an implementation of Multimap, to avoid messy null-checking code. to be honest, it doesn't get much shorter than your solution:
public List<Activity> groupedByDate(List<Activity> input) {
//group by day
final Multimap<DateMidnight, Activity> activityByDay
= Multimaps.index(input, new Function<Activity, DateMidnight>() {
#Override
public DateMidnight apply(Activity from) {
return new DateMidnight(from.activityDate);
}
});
//for each day, sum up amount
List<Activity> ret = Lists.newArrayList();
for (DateMidnight day : activityByDay.keySet()) {
Activity ins = new Activity();
ins.activityDate = day.toDate();
for (Activity activity : activityByDay.get(day)) {
ins.amount+=activity.amount;
}
}
return ret;
}
Why not simply create a HashMap<Date, Activity>() instead of the roundabout way with Strings?
Sorry, I didn't answer the question. The answer is: yes, unless I am an idiot ;)
You could do this using the Date as the key if you used a TreeMap and provided a Comparator that only compared the year, month and day and not the time.
As already mentioned the best solution is to represent your date with day precission. If this is not possible joda is nice library.
If you can ignore daylight saving time then grouping by date can be accomplished much easier. A unix time day is 86 400 s long. The timestamp does ignore leap seconds. (Your timer stops for one second or the leap second is distributed in some way.) All date values were day is equal are the same day:
int msPerDay = 86400 * 1000;
long day = new Date().getTime() / msPerDay
One minor point is to adjust the timezone. For my timezone CET (UTC/GMT +1 hour) the GMT day starts one our later:
new GregorianCalendar(2009, 10, 1, 1, 0).getTime().getTime() / msPerDay) ==
new GregorianCalendar(2009, 10, 2, 0, 59).getTime().getTime() / msPerDay) ==
new Date().getTime() / msPerDay
If the daylight saving time is significant the best way is to use joda. The rules are just to complicated and locale specific to implement.