Java decimal to date value - java

I'm attempting something and I'm not quite sure how to approach it. I have two user defined values.....a duration and a duration unit. At this point I will already have a start date, so I want to apply the duration and durationUnit somehow to startDate to get the endDate.
Duration is a decimal, durationUnit a HardCode/AbstractCode value and startDate is a Date.
So if the startDate is 17/12/2010......and the user enters the following;
Duration: 3
Duration Unit: Months
I want the endDate to then be calculated as 17/03/2011. Any idea on how I could do this? The duration unit could be Days, Months or Years.
Thanks in advance!

Have a look at joda-time. It's a superb replacement for Date/Calendar. You can do things like:
DateTime newDate = startDate.plusDays(days);
.plusYears(years);
Period toAdd = periodFormatter.parse(inputString);
DateTime newDate = startDate.plus(toAdd);

You can map the Day/Month/Year to the appropriate Calendar DAY, MONTH or YEAR. Then use calendar.add().
If by decimal you mean a double then you will probably have to do some processing to turn parts of a value into appropriate values (such as changing .5 DAY to 12 hours).

DateFormatter is also of use if you want a date to be represented in different styles.
Here, for the sake of brevity, the methods are invoked on classes which you should instatiate first whether using a factory or a constructor. The following statements are only for grasping the idea. Consult JavaDoc API for further details.
Calendar.set(...) //(to set year, month and day).
Calendar.add(...)//(to add a value on specific unit (month, day or year))
Calendar.getInstance() //(return Date object)
DateFormat.format(..) //(return a String representing a style used at instantiation of //DateFormat)

Haven't you tried using the Date type
Date myDate = new Date();
myDate.setMonth();
myDate.setDay();
I haven't use it myself, so i can really, tell you i f it really works, but you shoul give it a try

Others said it already, here a more concrete sample using java.util.Calendar:
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
if(durationUnit.equals("day")){
cal.add(Calendar.DATE, duration);
} else if(durationUnit.equals("month")){
cal.add(Calendar.MONTH, duration);
} else if(durationUnit.equals("year")){
cal.add(Calendar.YEAR, duration);
}
Date endDate = cal.getTime();

Related

Calendar.getTime().getYear() gives back 0113 instead of 2013

I'm making a little game. When the game is starting for the first time i saves the time since 01.01.1970 in seconds in the SharedPreferences.
Now i want to give this date out on my screen in this form: DD.MM.YYYYY
I used the Calendar function but it give back 02.04.0113 so, there are missing 1900 Years.
Here is my Code:
private void initBornTXT() {
SharedPreferences pref = getSharedPreferences("LIFE", 0);
long born = pref.getLong("BIRTHDAY", 0);
Calendar c = Calendar.getInstance();
c.setTimeInMillis(0);
c.add(Calendar.SECOND, (int)born);
int year = c.getTime().getYear();
int month = c.getTime().getMonth();
int day = c.getTime().getDay();
String string_born = String.format("%02d.%02d.%04d", day, month, year);
TextView born_txt = (TextView)findViewById(R.id.textViewBorn);
born_txt.setText(string_born);
}
What coud be wrong?
Nothing's wrong. You've just not looked at the documentation for the method you're calling, Date.getYear():
Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
Note that you should have received a warning that you're using a deprecated API: don't just ignore those warnings.
Also, do yourself a favour and don't do the formatting yourself: use SimpleDateFormat instead. (Or ideally, use Joda Time instead...) That way you can avoid the month being wrong, too... you may not have noticed that you're a month off due to months being 0-based, which is common to both Calendar and Date.
That's normal, documented behavior. See JavaDoc for Date#getYear().
A better way to get the year would be:
c.get(Calendar.YEAR)
You're using getTime, which returns a date object. Dates are based on 0=1900. So this is the expected output. Use a SimpleDateFormat instead.
Kudos for creating a Y2K bug though :)

How to generate a Date from just Month and Year in Java?

I need to generate a new Date object for credit card expiration date, I only have a month and a year, how can I generate a Date based on those two? I need the easiest way possible. I was reading some other answers on here, but they all seem too sophisticated.
You could use java.util.Calendar:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEAR, year);
Date date = calendar.getTime();
java.time
Using java.time framework built into Java 8
import java.time.YearMonth;
int year = 2015;
int month = 12;
YearMonth.of(year,month); // 2015-12
from String
YearMonth.parse("2015-12"); // 2015-12
with custom DateTimeFormatter
import java.time.format.DateTimeFormatter;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM yyyy");
YearMonth.parse("12 2015", formatter); // 2015-12
Conversions
To convert YearMonth to more standard date representation which is LocalDate.
LocalDate startMonth = date.atDay(1); //2015-12-01
LocalDate endMonth = date.atEndOfMonth(); //2015-12-31
Possibly a non-answer since you asked for a java.util.Date, but it seems like a good opportunity to point out that most work with dates and times and calendars in Java should probably be done with the Joda-Time library, in which case
new LocalDate(year, month, 1)
comes to mind.
Joda-Time has a number of other nice things regarding days of the month. For example if you wanted to know the first day of the current month, you can write
LocalDate firstOfThisMonth = new LocalDate().withDayOfMonth(1);
In your comment you ask about passing a string to the java.util.Date constructor, for example:
new Date("2012-09-19")
This version of the constructor is deprecated, so don't use it. You should create a date formatter and call parse. This is good advice because you will probably have year and month as integer values, and will need to make a good string, properly padded and delimited and all that, which is incredibly hard to get right in all cases. For that reason use the date formatter which knows how to take care of all that stuff perfectly.
Other earlier answers showed how to do this.
Like
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM");
Date utilDate = formatter.parse(year + "/" + month);
Copied from Create a java.util.Date Object from a Year, Month, Day Forma
or maybe like
DateTime aDate = new DateTime(year, month, 1, 0, 0, 0);
Copied from What's the Right Way to Create a Date in Java?
The most common sense approach would be to use the Date("YYYY-MM-DD") constructor even though it is deprecated. This is the easiest way to create a date on the fly. Screw whoever decided to deprecate it. Long live Date("YYYY-MM-DD")!!!
Don’t use this answer. Use the answers by Przemek and Ray Toel. As Przemek says, prefer to use a YearMonth for representing year and month. As both say, if you must use a date, use LocalDate, it’s a date without time of day.
If you absolutely indispensably need an old-fashioned java.util.Date object for a legacy API that you cannot change, here’s one easy way to get one. It may not work as desired, it may not give you exactly the date that you need, it depends on your exact requirements.
YearMonth expiration = YearMonth.of(2021, 8); // or .of(2021, Month.AUGUST);
Date oldFashionedDateObject = Date.from(expiration
.atDay(1)
.atStartOfDay(ZoneId.systemDefault())
.toInstant());
System.out.println(oldFashionedDateObject);
On my computer this prints
Sun Aug 01 00:00:00 CEST 2021
What we got is the first of the month at midnight in my local time zone — more precisely, my JVM’s time zone setting. This is one good guess at what your legacy API expects, but it is also dangerous. The JVM’s time zone setting may be changed under our feet by other parts of the program or by other programs running in the same JVM. In other words, we cannot really be sure what we get.
The time zone issue gets even worse if the date is transmitted to a computer running a different time zone, like from client to server or vice versa, or to a database running its own time zone. There’s about 50 % risk that your Date will come through as a time in the previous month.
If you know the time zone required in the end, it will help to specify for example ZoneId.of("America/New_York") instead of the system default in the above snippet.
If your API is lenient and just needs some point within the correct month, you’ll be better off giving it the 2nd of the month UTC or the 3rd of the month in your own time zone. Here’s how to do the former:
Date oldFashionedDateObject = Date.from(expiration
.atDay(2)
.atStartOfDay(ZoneOffset.UTC)
.toInstant());

Find a day according to date in android

I have 2 questions:
How can I find what is the day of the week according to a specific date in JAVA ?
I want to find a difference between 2 times (each time include date and hour) in Java or PHP, someone can help me with that?
Thanx,
EDIT:
I still have a problem with that, I dont success to find the date of a specific date... i'm trying 2 ways, boths are not working.
1.
GregorianCalendar g = new GregorianCalendar(year, month, day, hour, min);
int dayOfWeek=g.DAY_OF_WEEK;
2.
Calendar cal = Calendar.getInstance();
cal.set(year, month, day, hour, min);
int dayOfWeek2 = cal.get(Calendar.DAY_OF_WEEK);
Someone cane give me another solution?
While not particularly great, the standard Java Calendar class should be sufficient for solving your first problem. You can set the time of a Calendar instance using a Date object, then access the DAY_OF_WEEK field. Something like this:
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
As for the second problem, it depends how you want the difference to be measured. If you just want the difference in milliseconds, you can simply call the getTime() method on each of your Date instances, and subtract one from the other. If you want it in terms of seconds, minutes, hours, days, etc you can simply do some simple arithmetic using that value.
Refer these links,
Find day of the week
to find the day of the week according to a specific date
try like below,
Calendar calendar=Calendar.getInstance();
calendar.setTime(specific_date);
int weekday = calendar.get(Calendar.DAY_OF_WEEK);
Find the difference between two times

Want only date from epoch

Given millis since epoch, I want an instance with the fields Month, Date, Year filled out, with the hour minute seconds set to some default values.
What is an efficient way to do this?
I know that there are sql ways to do it but is there a way to do it in Java?
Just use:
new Calendar(new Date(msSinceEpoch));
where the ms is a long value.
Use either LocalDate or DateMidnight in the Joda-Time API. The differences are explained in the javadocs.
Note that in order to truncate a point in time (some millis since epoch) to a specific calendar day, you might want to specify when midnight happened, or else you'll end up with midnight in the system's timezone. For example, you might call the LocalDate(long, DateTimeZone) constructor instead of the LocalDate(long) constructor.
Or, if you'd rather not have a JODA dependency, use DateFormat:
Date thisDate = new SimpleDateFormat("yyyy-MMM-dd").parse("2011-Jun-29");
Per the javadocs, you can easily create a Date from a long:
long value = System.currentTimeMillis();
Date thisDate = new Date(value);

Java: Is this a correct way to get the current time as a Calendar object in a particular time zone?

I know there are other similar questions to this, but I came up with my own way of getting the current time in a specific time zone, so I just wanted to confirm if it is correct or not, or there are gotchas I didn't take care of.
Calendar cal = Calendar.getInstance();
// Assuming we want to get the current time in GMT.
TimeZone tz = TimeZone.getTimeZone("GMT");
cal.setTimeInMillis(calendar.getTimeInMillis()
+ tz.getOffset(calendar.getTimeInMillis())
- TimeZone.getDefault().getOffset(calendar.getTimeInMillis()));
// Calendar should now be in GMT.
Is the above correct at all? I did my own test and it seemed to be working as expected, but just wanted to confirm it again with the experts in Stack Overflow.
If you simply do a Calendar.getInstance with the TimeZone argument, the calendar's internal state for the get() methods will return you the field with the time for that timezone. For example:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
// if i run this at 9 EST this will print 2
System.out.println(cal.get(Calendar.HOUR));
If you just need the local time for display purposes, you can set the TimeZone on your format object. For example:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(new Date()));
Like Macarse said though, Joda time is where it's at if you need to do anything more complex. The Java date APIs are a nightmare.
I'd prefer using joda-time instead of that.
Check this link.

Categories