I've below code in Java 1.7:
DateFormat df = DateFormat.getInstance();
Date startDate = df.parse("07/28/12 01:00 AM, PST");
The above date time (07/28/12 01:00 AM, PST) is in the properties file which is configurable. If this date time is already passed, then I need to get the current date, set the time part from above string which is 01:00 AM PST in the current date & if this time is also already passed, then get the next day & set the time part from above string in it. The final object should be Date since I need to use it in Timer object.
How can I do this efficiently? Should I convert from date to Calendar or vice-versa? Can any one provide snippet?
You should look into the Calendar class. You can use constructs like:
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
cal.add(Calendar.DAY_OF_YEAR, 1);
It also has methods for checking if your startDate is before() or after() a new date (use the current time).
While writing of the built-in Java date/time structure, i would be remiss if i didnt plug Joda Time, considered by many to be superior to the native Java implementation.
EDIT:
It would be more efficient to show an example of the Date.compareTo() process, as the Calendar.before() and Calendar.after() require comparisons against other Calendar objects, which can be expensive to create.
take a look at the following:
DateFormat df = DateFormat.getInstance();
Date startDate = df.parse("07/28/12 01:00 AM, PST");
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
Date now = new Date();
if (startDate.compareTo(now)< 0) {
System.out.println("start date: " + startDate + " is before " + now);
Calendar nowCal = Calendar.getInstance();
nowCal.add(Calendar.DAY_OF_YEAR,1);
cal.set(Calendar.DAY_OF_YEAR, nowCal.get(Calendar.DAY_OF_YEAR));
} else if (startDate.compareTo(now) == 0) {
System.out.println("startDate: " +startDate + " is equal to " + now);
} else {
System.out.println("startDate: " + cal + " is after " + now);
}
System.out.println(cal.getTime());
I think this should work...your algorthim has my head spinning a little and I'm in a different time zone, so you original string didn't work :P
try {
DateFormat df = DateFormat.getInstance();
Date startDate = df.parse("28/07/2012 01:00 AM");
System.out.println("StartDate = " + startDate);
Date callDate = startDate;
Calendar today = Calendar.getInstance();
Calendar start = Calendar.getInstance();
start.setTime(startDate);
System.out.println("Today = " + today.getTime());
// If this date time is already passed
// Tue Jul 31 12:18:09 EST 2012 is after Sat Jul 28 01:00:00 EST 2012
if (today.after(start)) {
//then I need to get the current date, set the time part from above string in the current date
Calendar timeMatch = Calendar.getInstance();
timeMatch.setTime(startDate);
timeMatch.set(Calendar.DATE, today.get(Calendar.DATE));
timeMatch.set(Calendar.MONTH, today.get(Calendar.MONTH));
timeMatch.set(Calendar.YEAR, today.get(Calendar.YEAR));
//& if this time is also already passed, then get the next day & set the time part from above string in it
if (timeMatch.after(today)) {
timeMatch.add(Calendar.DATE, 1);
}
callDate = timeMatch.getTime();
}
System.out.println("CallDate = " + callDate);
} catch (ParseException exp) {
exp.printStackTrace();
}
This produces the following output
StartDate = Sat Jul 28 01:00:00 EST 2012
Today = Tue Jul 31 12:18:09 EST 2012
CallDate = Tue Jul 31 01:00:00 EST 2012
Related
From the below java code I'm getting a month First & last dateTimestamp, but here i need last dateTimestamp as - "Mon Aug 31 23:59:59 IST 2015" instead of - "Mon Aug 31 00:00:00 IST 2015"?
Calendar cal = Calendar.getInstance();
int year = 2015;
int month = 07;
cal.set(cal.DATE,1);
cal.set(cal.YEAR,year);
cal.set(cal.MONTH, month);
String firstDate = (cal.getActualMinimum(cal.DATE) + "/" + (month+1) + "/" +year);
System.out.println("firstDate-->"+"\t"+firstDate);
String lastDate = (cal.getActualMaximum(cal.DATE) + "/" + (month+1) + "/" +year);
System.out.println("lastDate-->"+"\t"+lastDate);
DateFormat firstFormat = new SimpleDateFormat("dd/MM/yyyy");
Date beginDate = firstFormat.parse(firstDate);
System.out.println("BeginDate Timestamp"+ "\t" + beginDate);
DateFormat secoundFormat = new SimpleDateFormat("dd/MM/yyyy");
Date endDate = secoundFormat.parse(lastDate);
System.out.println("endDate Timestamp"+ "\t" + endDate);
Output:->
firstDate--> 1/8/2015
lastDate--> 31/8/2015
BeginDate Timestamp Sat Aug 01 00:00:00 IST 2015
endDate Timestamp Mon Aug 31 00:00:00 IST 2015
Please help me if we have any solution.
If I understand your question, it looks as if you want to pass a year and month into a method, and get back the last day of the passed month.
I would suggest consider (in this order):
which jdk you use
configuration of calendar
configuration of timezone (maybe)
using jodatime
As of 1.8 many JodaTime-like features have been added to the jdk- e.g. see https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html (If you arent using 1.8 you can use the joda lib, assuming your organization allows it)
Calendar.getInstance() gives a default TimeZone and a default Locale, which means the definitions of the running JVM. You may or may not need to consider this and implement more than just getInstance(). See API javadoc.
Assuming a Gregeorian Calendar (hey, you could be Bahaian and have 19 months in the year ...) , here is one partial implementation using JDK 1.7, JodaTime jar 2.2, validation-1.0.0.GA jar:
#Test
public void testDate() {
final String dateStringOfFirstDay = "1.7.2015";
final Date lastDayOfMonth = getLastDayOfMonth(dateStringOfFirstDay);
Assert.assertNotNull(lastDayOfMonth);
//more assertions ...
}
private Date getLastDayOfMonth(#NotNull String dateStringOfFirstDay) {
//further validation here necessary according to required date format
DateTime dt = DateTime.parse(dateStringOfFirstDay);
return dt.dayOfMonth().withMaximumValue().toDate();
}
The defintion of DateFormat/DateTimeFormat and further result assertions is left up to you.
Best of luck!
Guys I got a solution for my question!!!
I think it will help u too...
Calendar calendar = Calendar.getInstance();
int year=2015;
int month=7;
int date=31;
int hourOfDay=23;
int minute=59;
int second=59;
int milliSecond=999;
calendar.set(year, month, date, hourOfDay, minute, second);
calendar.set(calendar.MILLISECOND, milliSecond);
System.out.println("Time from Calendar: "+calendar.getTime());
long timeInMilliSeconds=calendar.getTimeInMillis();
System.out.println("timeInMilliSeconds from calendar: "+timeInMilliSeconds);
Timestamp timestamp=new Timestamp(timeInMilliSeconds);
System.out.println(timestamp);
The above program gives the last date last timestamp in a selected month.
getTimeInMillis() takes the time from Jan 01, 1970 to current time in Milliseconds.
Using those milliseconds i'm getting the Timestamp.
Thank you for your help guys!!!
OutPut:->
Time from Calendar: Mon Aug 31 23:59:59 IST 2015
timeInMilliSeconds from calendar: 1441045799999
2015-08-31 23:59:59.999
This is my date
Thu Feb 20 18:34:00 GMT+5:30 2014
When I use getTimeInMillis() I'm geting a negative value(-5856679776000). It should be something positive. Can anyone tell me why?
The stored date i.e cal1 is giving a negative value while the second date i.e current date is a positive one.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",java.util.Locale.getDefault());
try {
java.util.Date d = format.parse(date+" "+time);
GregorianCalendar cal1 = new GregorianCalendar(d.getYear(),
d.getMonth(),
d.getDay(),
d.getHours(),
d.getMinutes());
Calendar cal = Calendar.getInstance();
GregorianCalendar cal2 = new GregorianCalendar(cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE));
Toast.makeText(getApplicationContext(),
"Stored date " + d +
"\nCurrent date " + cal.getTime() +
"\nStored date in ms :" + cal1.getTimeInMillis() +
"\nCurrent time in ms :" + cal2.getTimeInMillis()+
"\nDifference " + ((cal1.getTimeInMillis()-cal2.getTimeInMillis())/1000),
Toast.LENGTH_LONG).show();
}
catch(Exception e) {
Toast.makeText(getApplicationContext(),"Date parsing error", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
replace
new GregorianCalendar(d.getYear(), d.getMonth(), d.getDay(), d.getHours(), d.getMinutes());
with
new GregorianCalendar(1900+d.getYear(), d.getMonth(), d.getDay(), d.getHours(), d.getMinutes());
Check the documentation of getYear method. It returns years after 1900 ... And the second cause has been already identified by #Pakspul ..
You should swap cal1 and cal2 in your millisecond calculation. For example:
startdate = 12:00
enddate = 12:01
diff = enddate - startdate; // result is 1 minute
diff = startdate - enddate; // result is -1 minute
What you is doing here is that you are calling cal2 after cal1 so it will have definatly higher value than cal1 because it has the mostrecent time, hence the negative result value.
just switch them and try again like this:
Toast.makeText(getApplicationContext(),"Stored date "+d+"\nCurrent date "+cal.getTime()+"\nStored date in ms :"+cal1.getTimeInMillis()+"\nCurrent time in ms :"+cal2.getTimeInMillis()+"\nDifference "+((cal2.getTimeInMillis()-cal1.getTimeInMillis())/1000), Toast.LENGTH_LONG).show();
}
I am really confused with the result I am getting with Calendar.getInstance(TimeZone.getTimeZone("UTC")) method call, it's returning IST time.
Here is the code I used
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
and the response I got is:
Sat Jan 25 15:44:18 IST 2014
So I tried changing the default TimeZone to UTC and then I checked, then it is working fine
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
TimeZone tz = TimeZone.getDefault() ;
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Three = Calendar.getInstance();
System.out.println(cal_Three.getTime());
TimeZone.setDefault(tz);
Result:
Sat Jan 25 16:09:11 IST 2014
Sat Jan 25 10:39:11 UTC 2014
Am I missing something here?
The System.out.println(cal_Two.getTime()) invocation returns a Date from getTime(). It is the Date which is getting converted to a string for println, and that conversion will use the default IST timezone in your case.
You'll need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.
EDIT: Courtesy of #Laurynas, consider this:
TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);
System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();
System.out.println("UTC: " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());
java.util.Date is independent of the timezone. When you print cal_Two though the Calendar instance has got its timezone set to UTC, cal_Two.getTime() would return a Date instance which does not have a timezone (and is always in the default timezone)
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
System.out.println(cal_Two.getTimeZone());
Output:
Sat Jan 25 16:40:28 IST 2014
sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
From the javadoc of TimeZone.setDefault()
Sets the TimeZone that is returned by the getDefault method. If zone
is null, reset the default to the value it had originally when the VM
first started.
Hence, moving your setDefault() before cal_Two is instantiated you would get the correct result.
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
Calendar cal_Three = Calendar.getInstance();
System.out.println(cal_Three.getTime());
Output:
Sat Jan 25 11:15:29 UTC 2014
Sat Jan 25 11:15:29 UTC 2014
You are definitely missing a small thing and that is you are not setting a default value:
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
So the code would look like:
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
Explanation: If you want to change the time zone, set the default time zone using TimeZone.setDefault()
Calendar currentTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
currentTime.set(Calendar.ZONE_OFFSET, TimeZone.getTimeZone("UTC").getRawOffset());
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, currentTime.get(Calendar.HOUR_OF_DAY));
calendar.getTimeInMillis()
is working for me
Following code is the simple example to change the timezone
public static void main(String[] args) {
//get time zone
TimeZone timeZone1 = TimeZone.getTimeZone("Asia/Colombo");
Calendar calendar = new GregorianCalendar();
//setting required timeZone
calendar.setTimeZone(timeZone1);
System.out.println("Time :" + calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND));
}
if you want see the list of timezones, here is the follwing code
public static void main(String[] args) {
String[] ids = TimeZone.getAvailableIDs();
for (String id : ids) {
System.out.println(displayTimeZone(TimeZone.getTimeZone(id)));
}
System.out.println("\nTotal TimeZone ID " + ids.length);
}
private static String displayTimeZone(TimeZone tz) {
long hours = TimeUnit.MILLISECONDS.toHours(tz.getRawOffset());
long minutes = TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset())
- TimeUnit.HOURS.toMinutes(hours);
// avoid -4:-30 issue
minutes = Math.abs(minutes);
String result = "";
if (hours > 0) {
result = String.format("(GMT+%d:%02d) %s", hours, minutes, tz.getID());
} else {
result = String.format("(GMT%d:%02d) %s", hours, minutes, tz.getID());
}
return result;
}
It is working for me.
Get in Timestamp type:
public static Timestamp getCurrentTimestamp() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
final Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
Timestamp ts = new Timestamp(date.getTime());
return ts;
}
Get in String type:
public static String getCurrentTimestamp() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
final Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
Timestamp ts = new Timestamp(date.getTime());
return ts.toString();
}
Try to use GMT instead of UTC. They refer to the same time zone, yet the name GMT is more common and might work.
i am trying to print the date as : 2013/11/20 08 30 but it is printing as below after parsing the date through simpledateformat Wed Nov 20 14:00:00 IST 2013,
here i passed the HH and MM as 08 30 but after parsing it changed to 14:00:00
Can you please suggest
public class PrintDate {
public static void main(String[] args) {
System.out.println(getDate("2013/11/20","08","30"));
}
public static Date getDate(String date, String hour, String miniute) {
final SimpleDateFormat displayDateTimeFormat = new SimpleDateFormat("yyyy/MM/dd HH mm");
displayDateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String paddedHour = hour.length() == 2 ? hour : "0" + hour;
int min = Integer.valueOf(miniute);
int remainder = min % 5;
int roundMinute = remainder > 2 ? min - remainder + 5 : min - remainder;
String minuteStr = String.valueOf(roundMinute);
String paddedMinuteStr = minuteStr.length() == 2 ? minuteStr : "0" + minuteStr;
String startDateStr = date + " " + paddedHour.toUpperCase() + " " + paddedMinuteStr;
Date startDate = null;
try {
startDate = displayDateTimeFormat.parse(startDateStr);
} catch (ParseException e) {
}
return startDate;
}
}
after parsing the date through simpledateformat Wed Nov 20 14:00:00 IST 2013, here i passed the HH and MM as 08 30 but after parsing it changed to 14:00:00
Yes, because you specified that you wanted it to be parsed as a UTC value. However, the Date itself has no concept of a time zone - it's just an instant in time. Date.toString() will always use the default time zone.
2013-11-20 08:30 UTC is the same instant in time as 2013-11-20 14:00 IST, so it's actually parsing it correctly - it's just the result of Date.toString() which is confusing you.
If you want to preserve the time zone as well, you'll have to do that separately - or (better) use Joda Time which is a much nicer date/time API, and has a DateTime class which represents an instant in time in a particular calendar system and time zone.
Just try below lines of code to get date in desired format -
Date date=new Date(2013-1900,10,20,8,30);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyy/MM/dd K mm");
String strFormatDate = dateFormat.format(date);
Date dtFormatDate = dateFormat.parse(strFormatDate);
System.out.println("Formatted date in String:"+strFormatDate);
System.out.println("Formatted Date:"+dtFormatDate);
Just give K instead of HH in date format. You can give date as 14 30 then also this format will convert date as you desired.
Thanks
I'm trying to parse a date from a String and get the long value. The long value will be later sent to an SQL query.
here's my code:
String dayDate = "28-02-2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date day = new Date();
try {
day = sdf.parse(dayDate);
} catch (ParseException pe) {
pe.printStackTrace();
}
System.out.println("day : "+day.toString()+ " long : " + day.getTime());
which gives the following output:
day : Thu Feb 28 00:00:00 EET 2013 long : 1362002400000
which is correct but not what I want since the long value results in Wed, 27 Feb 2013 22:00:00 GMT (http://www.epochconverter.com/) (I'm in a GMT+2 timezone). And i need to send to correct long value to sql.
Is there anyway to work around this without using external libraries?
SimpleDateFormat is locale-aware, meaning the date it parses is in your timezone. Midnight 28 Feb in GMT+2 is actually 10pm 27 Feb in GMT, the long value 1362002400000. I would add this to get the parsing right (would't bother using Calendar):
sdf.setTimeZone(TimeZone.getTimeZone("GMT"))
Again, when you print this date it uses SimpleDateFormat and that's why you can see EET in the output.
Passing this to database is a different story though once you get this right.
Use DateFormat.setCalendar(Calendar cal) to set a Calendar with GMT as its timezone, or use DateFormat.setTimeZone(TimeZone zone) with the GMT TimeZone. That will ensure that the resulting Date will be 00:00:00 in GMT instead of in EET.
If you add a timezone specifier to your string you can force java to use GMT for the conversion:
String dayDate = "28-02-2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy z"); // z is a timezone specifier
Date day = new Date();
try {
day = sdf.parse(dayDate + " GMT"); // Use GMT timezone.
} catch (ParseException pe) {
pe.printStackTrace();
}
System.out.println("day : "+day.toString()+ " long : " + day.getTime());
You are converting between text and internal (Date) representations of dates and times without explicitly stating the time-zone. That never goes well.
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
Date date = calendar.getTime();
Use your timezone String:
TimeZones