How can you save time by using the built in Date class? - actionscript-3

The intention of this question is to gather solutions to date / time calculation using the built in Date class instead of writing long complicated functions.
I’ll write some answers myself, and accept an answer if anyone comes up with something very clever. But this is mostly meant as a collection of solutions, since I often see overly complicated code for handling dates.
Please remember this is not for long solutions for things the Date class can not do.
A good place to start is the reference found here:
http://help.adobe.com/en_US/AS3LCR/Flash_10.0/Date.html

You can easily find out if a year was a leap year without coding all the exceptions to the rule by using the Date class. By subtracting one day from marts the 1st (requesting marts the 0th), you can find the number of days in February.
Remember that month is zero-indexed so Marts being the 3rd month has index 2.
function CheckIfYearIsLeapYear(year:uint):Boolean
{
return new Date(year, 2, 0).Date == 29;
}

To properly compare to dates you need to use the getTime() function, it will give you the time in milliseconds since January 1, 1970. Which makes it easy to compare to dates, a later date will return a larger value.
You can subtract one from the other to get the difference, but unfortunately there is no built in time span class to handle this cleanly; you will have to use a bit of math to present the difference properly to the user (eg. dividing the difference with the number milliseconds in a day to get the difference in days).
var date1:Date = new Date(1994, 12, 24);
var date2:Date = new Date(1991, 1, 3);
if(date1.getTime() > date2.getTime())
trace("date1 is after date2");
else
trace("date2 is after or the same as date1");

There's also ObjectUtil.dateCompare(a,b)

To get the current system date simply create a new Date object without passing any values to the constructor. Like this:
var today:Date = new Date();
trace("The date and time right now is: " + today. toLocaleString());
trace("The date right now is: " + today. toLocaleDateString());
trace("The time right now is: " + today. toLocaleTimeString());

The built in Date class handles “overflow” very well, this can be used to add or subtract time. If one of the fields overflows, the date class handles it by adding or subtracting the overflow.
var date:Date = new Date(1993, 12, 28);
trace("7 days after the " + date.toLocaleDateString());
date.setDate(date.Date + 7);
trace("It was the " + date.toLocaleDateString());

Related

EOMONTH equivalent in Google Scripts

I'm writing a script that doing some date manipulation and I need to know how many days between current date and end of the month.
I've already got a function that I can put two dates into and it'll return the number of days between the two dates.
I'm looking for an equivalent of EOMONTH in scripts so I can return the date of the last day of any given month
(Hope that makes sense)
All I've been able to come up with so far is adding a day to the date until it becomes a new month and running a counter whilst doing so, but this just seems a really silly way of doing it.
function daysInMonth(m=0) {
return new Date(new Date().getFullYear(),m+1,0).getDate();
}

Converting timer format hh:mm to decimal format hh.decimal(mm) in Business Objects

The aim is to create a new data column based on a current time formatted colum.
For example I want to have 4:20 -> 4.33. I can't find a way of manipulating the time format to extract the hours and minutes seperatly to use hours + (minutes / 60).
Any help appreciated. Thank you.
To pick specific parts out of a datetime object you need to use the FormatDate() function. It returns a string which you need to convert to a number with the ToNumber() function before adding the hours and minutes together. So let's create a few variables...
Current DateTime=CurrentDate()
Hours=ToNumber(FormatDate([Current DateTime];"hh"); "##")
Minutes=ToNumber(FormatDate([Current DateTime];"mm"); "##")
Hours Minutes Decimal=[Hours] + ([Minutes]/60)
If you want to put this all together in one variable you can certainly do that...
Hours Minutes Decimal All in One=ToNumber(FormatDate(CurrentDate();"hh"); "##") + (ToNumber(FormatDate(CurrentDate();"mm"); "##")/60)
To locate documentation on what values correspond to which parts of the datetime value do the following...
Navigate to the FormatDate() function in the Variable Editor.
Click on "More on this function" in the lower right corner.
Click on "Custom Formats"

How do I write a query that works in both HSQLDB and MySQL to add days to a date in the WHERE clause?

I'd like to add a specific number of days to a date column and then compare that to the current date. Is there any way I can achieve this that is compatible with both HSQLDB (for testing) and MySQL (production)?
To make things even more complicated, I am using Hibernate.
Don't know the background of your problem, but can you do it the other way around: compare dae column with current date substracted by number of days?
I meant something like this in hql (I'm using jpql in this example, if you prefer JPA interface):
TypedQuery<SomeClass> q = getEntityManager().crateQuery(
"select s from SomeClass s where s.date = :date", SomeClass.class);
Calendar now = Calendar.getInstance();
// subtract number of days from current date, e.g. 10 days
now.add(Calendar.DAY, -10);
q.setParameter("date", now);
List<SomeClass> = q.getResultList();
This approach is database-agnostic, but of course works only for trivial cases, in some mor e complicated cases it will not work.

As3 Date Object Not Returning Hours Correctly

So I have a really simple, yet annoying problem. I am creating a date object and calling the getHours() method and the return seems to always be zero. Perhaps I am doing something wrong?
var d:Date = new Date(1382166000000); // 10 / 19 / 13 # 2:00:00am EST
trace(d.getTime() + " : " + d.getHours());
//output: 1382166000000 : 0
Any ideas? Unless I am monumentally confused shouldn't getHours be returning 2?
Date doesn't work the way you think it does. It can exist in one of two formats: the local time or UTC.
The getHours() method returns local time, or the UTC time formatted according to the computer's internal timezone offset. The time you passed is actually 7AM in UTC. So by that logic, you (and I) are in PST (or UTC-7). If you run d.timezoneOffset, it should return 420, which is 7 hours in minutes.
Now, most of the time you never want to work with anything except UTC (UTC is a constant, especially in computers). So forget the getHours() method and look at getUTCHours() instead.
trace(d.getTime() + " : " + d.getUTCHours ()); // output 1382166000000 : 7
So that will give you the time in UTC hours. Next, you have to determine what time zone you want to format it as. EST is UTC-5, so you want to subtract 5 from the UTC hours.
trace(d.getTime() + " : " + ( d.getUTCHours () - 5 )); // output 1382166000000 : 2
And that gives you exactly what you were expecting.
Just to reiterate: AS3's Date class does not allow for setting the timezone. You only have access to the time in UTC and in the local time zone. Nothing more. If you want time in any other time zone, you need to format it manually, as I did above.

How to set up GUI date input to retain format look and feel

Okay I've tried this a few different ways and haven't been able to get it to do what I want it to. I've also visited this page: http://www.exampledepot.com/egs/javax.swing.text/formtext_FormTextDate.html
I have a spinner:
SimpleDateFormat datePattern = new SimpleDateFormat("MM/dd/yyyy");
JLabel endLabel = new JLabel("End Date: ");
JSpinner endSpinner = new JSpinner(new SpinnerDateModel());
endSpinner.setEditor(new JSpinner.DateEditor(endSpinner, datePattern.toPattern()));
This automatically loads today's date. I would prefer it to just show MM/DD/YYYY within the actual gui. This would give it the look of being date input without requiring a specific date to be entered if not required. Then as soon as you start spinning it would take a date. I can't seem to figure out how to do this. Any suggestions? I've also started looking up FormattedTextFields as well as an option. Would this be a better route to go?
If so, how can I set up the FormattedTextField to look like this: [ / / ]. Then when you put input in, keep that format, requiring only digits and 2 digits for month, 2 digits for day, and 4 digits for year. I would assume I'd have to set up some sort of pattern instead of initializing the FormattedTextField as a date? For example:
JFormattedTextField date = new JFormattedTextField(new SimpleDateFormat("MM/dd/yyyy"));
date.setValue(" / / ");
But all you would have to do is clear out the field and it would no longer look like a date. I want it to at least keep the '/' no matter what you do.
Sorry for the long drawn out question.