java - Creating a custom Date object from Calendar? -


i need create custom date object. user input in 24 hr format hh:mm i.e. 17:49 hrs. want set hours , minutes 17 , 49 respectively keeping other details month , year , day per current time.for e.g if today dec 16,2014 , time 16:00 hrs , want date object dec 16,2014 time 17:49 hrs. know can using deprecated apis , not want use them.i need date object because need pass java timer java timer not support calendar object.

the user input comes string , can parse string using new simpledateformat(hh:mm) contructor. tried using calendar.set apis had no success.

could 1 give direction on how proceed.

ps. sorry , can't use joda time :)

edit

since gethours() , getminutes() deprecated , have been replaced calendar.hour_of_day , calendar.minute respectively, use intermediary calendar object or set year , day current values.


there problem though, if input next day hour 24:01 won't move next day. previous answer, splitting of string did 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 current date     calendar.settime(date); //set date day january 1 1970, because parsed time part, date objects assumes start it's lowest value, try system.out.println(date) before 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 set time, extract date .gettime() method, returns java.util.date

the idea split string 2 parts based on separator :.

then initialize calendar , set hour , minutes 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 don't care seconds     final date mydate=cal.gettime(); //assign date object need calendar     //use mydate object anyway want ...     system.out.println(mydate); } 

Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -