I need to create a custom Date object. I get a user input in 24 hr format like hh:mm i.e. 17:49 hrs.
I want to set the hours and minutes as 17 and 49 respectively keeping other details like month , year , day as per the current time.For e.g if today is Dec 16,2014 and the time is 16:00 hrs , then i want a date object as Dec 16,2014 with time as 17:49 hrs. I know i can do this using deprecated apis , however i do not want to use them.I need the date object because i need to pass it to a java timer as java timer does not support any calendar object.
The user input comes as a string and i can parse that string using new SimpleDateFormat(HH:mm) contructor.
I tried using the Calendar.set apis but had no success.
Could some one give some direction on how to proceed.
PS. Sorry , i can't use Joda time :)
EDIT
Since getHours() and getMinutes() are deprecated and have been replaced with Calendar.HOUR_OF_DAY and Calendar.MINUTE respectively, you could use an intermediary calendar object or set the YEAR and DAY to current values.
There is a problem though, if you input next day hour like 24:01 it won't move to the next day. The previous answer, with splitting of string did the overflowing correctly.
public static void main(String[] args) throws ParseException {
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
final String timeInterval = "12:01";
Date date = simpleDateFormat.parse(timeInterval);
final Calendar calendar = Calendar.getInstance(); //calendar object with current date
calendar.setTime(date); //set date with day january 1 1970, this is because you parsed only the time part, the date objects assumes you start from it's lowest value, try a System.out.println(date) before this to see.
calendar.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));
calendar.set(Calendar.DATE,Calendar.getInstance().get(Calendar.DATE));
calendar.set(Calendar.MONTH, Calendar.getInstance().get(Calendar.MONTH))
date = calendar.getTime();
System.out.println(date);
}
You can use Calendar to set the time, then extract the date with .getTime() method, which returns a java.util.Date
The idea is to split your string into two parts based on the separator :.
Then simply initialize the calendar and set the hour and minutes with those values.
public static void main(String[] args) throws ParseException {
final String userInput = "17:49";
final String[] timeParts=userInput.split(":");
Calendar cal=Calendar.getInstance(); //current moment calendar
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeParts[0]));
cal.set(Calendar.MINUTE, Integer.parseInt(timeParts[1]));
cal.set(Calendar.SECOND,0); //if you don't care about seconds
final Date myDate=cal.getTime(); //assign the date object you need from calendar
//use myDate object anyway you want ...
System.out.println(myDate);
}
The following code works fine , however i don't want to use any deprecated apis.
...
...
String timeInterval = "18:01";
Date date = simpleDateFormat.parse(timeInterval);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, date.getHours());
calendar.set(Calendar.MINUTE, date.getMinutes());
date = calendar.getTime();
System.out.println(date);
...
...
Related
I have two functions which convert a date String to a date in milliseconds:
public static long convertYYYYMMDDtoLong(String date) throws ParseException {
SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd");
Date d = f.parse(date);
long milliseconds = d.getTime();
return milliseconds;
}
If I run this function I get the following result:
long timeStamp = convertYYYYMMDDtoLong("2014-02-17");
System.out.println(timeStamp);
It prints:
1389909720000
Now, if I run the following code:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeStamp);
System.out.println(cal.getTime());
It prints out:
Fri Jan 17 00:02:00 IST 2014
Why is my date shifted by one month? What is wrong?
P.S: My problem is that I need to map the date, represented as long, to another third party API which accepts Calendar format only.
You're using mm, which is minutes, not months. You want yyyy-MM-dd as your format string.
It's not clear why you're not returning a Calendar directly from your method, mind you:
private static final TimeZone UTC = TimeZone.getTimeZone("Etc/UTC")
public static Calendar convertYYYYMMDDtoCalendar(String text) throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
format.setTimeZone(UTC);
Calendar calendar = new GregorianCalendar(UTC);
calendar.setDate(format.parse(text));
return calendar;
}
(That's assuming you want a time zone of UTC... you'll need to decide that for yourself.)
I have Date today=new Date(); which returns the current date.. but when i try to display date,month,year separately with the help of
DateFormat mmFormat=new SimpleDateFormat("MM");
System.out.println(mmFormat.format(today.getMonth()));
DateFormat yyFormat=new SimpleDateFormat("yyyy");
System.out.println(yyFormat.format(today.getYear()));
it prints month as 01 and year as 1970
how to resolve this.?
mmFormat.format(today.getMonth())
You're passing an integer – the month of the date – to a date format method.
The format method interprets that integer as a UNIX timestamp – a number of seconds since 1970.
You need to pass the date itself to the formatter.
Pass the entire date to SimpleDateFormat. The format string "MM" or "yyyy" will cause it to just extract the part of the date you want.
Just use the Date today as the input argument
System.out.println(mmFormat.format(today));
and
System.out.println(yyFormat.format(today));
today.getMonth() and today.getYear() returns an int which is interpreted as an UNIX timestamp . The value is 1 and 113 , which corresponds to approximately January 1, 1970, 00:00:01 GMT and January 1, 1970, 00:01:53 GMT represented by this Date object. To get the desired result , you need to pass the Date object :
System.out.println(mmFormat.format(today));
You would need to use Calendar. Have a look at the java docs.
You can do it like this -
Calendar cal = Calendar.getInstance();
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.MONTH)); // month in the Calendar class begins from 0
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(cal.get(Calendar.MINUTE));
System.out.println(cal.get(Calendar.SECOND));
This would help you to avoid creating multiple DateFormat objects. Also in case you want to use another date instead of today's date the you can just pass the date to the cal.setTime() method.
That is because all these methods are deprecated. Use
Calendar myCalendar = GregorianCalendar.getInstance();
myCalendar.get(Calendar.MONTH);
myCalendar.get(Calendar.YEAR);
myCalendar.get(Calendar.DAY_OF_MONTH);
Better in this way
Date date=new Date(); // your date
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println(year+"\n"+month);
Turkey has two TimeZone GMT+2 and GMT+3.
I want to change the GMT+2 dates into GMT+3, but I want to protect hours and minutes that in GMT+2 TimeZone.
I want to take hours and minutes, and then set these values into GMT+3 TimeZone date. At result there must be no change in hours and minutes but the timeZone must be change only. At function toconvert date is must be GMT+2 format, but the return value must be GMT+3 format. How to do it clearly?
public static Date convertTimezone(Date toConvert) {
Date date = new Date();
date.setYear(toConvert.getYear());
date.setMonth(toConvert.getMonth());
date.setHours(toConvert.getHours());
date.setMinutes(toConvert.getMinutes());
return date;
}
In Java a Date represents a point in time, nothing else. This means that Date knows nothing about how it is printed, which time zone etc...
Time Zone is therefore something you set when printing the Date. The class DateFormat is typically used for printing and the time zone is part of the properties you can set on DateFormat. Typically, people use the subclass SimpleDateFormat.
java.util.Date cannot track your Timezone details. Use Calendar instead
You shouldn't use a Date object in this case. Use Calendar instead.
public static Calendar convertTimezone(Calendar toConvert) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+3"));
calendar.set(Calendar.YEAR, toConvert.get(Calendar.YEAR));
calendar.set(Calendar.MONTH, toConvert.get(Calendar.MONTH));
calendar.set(Calendar.DATE, toConvert.get(Calendar.DATE));
calendar.set(Calendar.HOUR_OF_DAY, toConvert.get(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, toConvert.get(Calendar.MINUTE));
return calendar;
}
You can make use of Calender API to convert one timezone to other
public static Date convertTimezone(Date toConvert) {
Calender calendar = Calendar.getInstance();
calender.setTime(toConvert);
int hour = calender.get(Calender.HOUR_OF_DAY);
int minutes = calender.get(Calender.MINUTE);
Calendar ret = new GregorianCalender(timeZone); //timeZone is destination TimeZone
ret.setTimeInMillis(calendar.getTimeInMillis() +
timeZone.getOffset(calendar.getTimeInMillis()) -
TimeZone.getDefault().getOffset(calendar.getTimeInMillis()));
ret.set(Calender.HOUR_OD_DAY, hour);
ret.set(Calender.MINUTE, minutes);
return ret.getTime();
}
I am using the below code to set an alarm. I would like to output what the time for this would be. I don't know if I going about this the wrong way. If I output the variable cal it has a long string of information. How do I extract only the hour and minutes?
Calendar cal = Calendar.getInstance();
// add 5 minutes to the calendar object
cal.add(Calendar.MINUTE, 464);
You can use the static constants as m0skit0 says, or use SimpleDateFormat. Here's some code to show both methods:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 464);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
System.out.println(sdf.format(cal.getTime()));
System.out.println(cal.get(Calendar.HOUR)+":"+cal.get(Calendar.MINUTE));
outputs:
05:31
5:31
Use the get() method on your Calendar object, and use Calendar static constants for the needed field (hour, minute, etc...).
For example:
cal.get(Calendar.Minute);
Given a String that is simply a day, for example, "Thu" or "Thursday", how would I get a java.util.Calendar object where the day String represents the closest String to today. In other words, today is Monday, 3/26/29012, so if the String were "Thu", I would want to form a date that represents "3/29/2012". If the String passed in is "Mon" and we're on Monday, I would want today's date. In this example, "3/26/2012".
I tried this ...
final DateFormat formatter = new SimpleDateFormat("EEE");
java.util.Date date = (Date) formatter.parse(dayOfWeekStr);
final Calendar now = Calendar.getInstance();
dateCal.set(Calendar.YEAR, now.get(Calendar.YEAR));
dateCal.set(Calendar.MONTH, now.get(Calendar.MONTH));
dateCal.setTime(date);
but it isn't working. Once I set the date, the year and month results to 1970, January.
You are almost there. Just put .setTime(..) ontop of the rest. Currently you are overriding your YEAR and MONTH changes by setting the time.
As Kevin noted, it might not work in all cases. For that reason I'd suggest you use a different approach: get only the DAY_OF_WEEK from a calendar, based on the parsed date, and set it to now. Of course, you should take care of changing the week if you need to.
I ended up going with
public static Calendar getNearestDateFromDayString(final String dayOfWeekStr,
final Calendar startingDay) throws ParseException {
final DateFormat formatter = new SimpleDateFormat("EEE");
final java.util.Date date = (Date) formatter.parse(dayOfWeekStr);
final Calendar result = Calendar.getInstance();
result.setTime(date);
result.set(Calendar.YEAR, startingDay.get(Calendar.YEAR));
result.set(Calendar.MONTH, startingDay.get(Calendar.MONTH));
result.set(Calendar.HOUR, startingDay.get(Calendar.HOUR));
result.set(Calendar.MINUTE, startingDay.get(Calendar.MINUTE));
result.set(Calendar.SECOND, 0);
java.util.Date today = new java.util.Date();
while (result.getTimeInMillis() <= today.getTime()) {
result.add(Calendar.DATE, 7);
} // while
return result;
} // getNearestDateFromDayString
If anyone has a more concise solution, I'll accept that instead.