I have two java.util.Date instances which is contain date value and time value. now I want to combine these values to create single java.util.Date instance representing the date and time.
here some example to make clear what I'd want :
Date date = 2015-06-01;
Date time = 22:30;
combine into :
Date dateTime = 2015-06-01 22:30;
I do some search and I found this question
Combining java.util.Dates to create a date-time
which is similar with my current issue. But the chosen answer on that question is deprecated.
You can do it without JODA, by using Calendar
However, as you asked about JODA, here is the way to do in JODA:
// you want the date part from it
Date d = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2013-01-02 03:04:05");
// you want to time part from it
Date t = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2014-02-03 04:05:06");
LocalDate datePart = new LocalDate(d);
LocalTime timePart = new LocalTime(t);
LocalDateTime dateTime = datePart.toLocalDateTime(timePart);
Date result = dateTime.toDate();
// Or shrink the above 4 lines into one, as follow
// Date result = new LocalDate(d).toLocalDateTime(new LocalTime(t)).toDate();
System.out.println("result " + result);
// print out result Wed Jan 02 04:05:06 CST 2013
Use a Calendar instead?
In particular, set(int year,
int month,
int date,
int hourOfDay,
int minute) and
if you want a Date, use getTime() ?
or convert the Date object to a Calendar object using the setTime(Date ..) function from the Calendar class, extract the values (day, hours, minute) using functions from the Calendar class?
I am trying to get the CalendarView widget to display only 1 week from current date. I tried using ,
Date date = new Date();
cal = (CalendarView) findViewById(R.id.calendarView1);
cal.setMaxDate(date.getTime()+604800000);
cal.setMinDate(date.getTime());
but it doesn't seem to work. Really appreciate if someone could help me out.
u can set like this here eg. i set the date to 25 -12(december)- current year. You want something like: just get 1 week from current date and u can set like this also
public static Calendar defaultCalendar() {
Calendar currentDate = Calendar.getInstance();
currentDate.set(Calendar.MONTH, 11); // Months are 0-based!
currentDate.set(Calendar.DAY_OF_MONTH, 25); // Clearer than DATE
return currentDate;
}
I m facing a problem:I want to get current time of GMT TimeZone in long.
I m using the following code as given below:
TimeZone timeZoneGmt = TimeZone.getTimeZone("GMT");
long gmtCurrentTime = getCurrentTimeInSpecificTimeZone(timeZoneGmt);
public static long getCurrentTimeInSpecificTimeZone(TimeZone timeZone) {
Calendar cal = Calendar.getInstance();
cal.setTimeZone(timeZone);
long finalValue = 0;
SimpleDateFormat sdf = new SimpleDateFormat(
"MMM dd yyyy hh:mm:ss:SSSaaa");
sdf.setTimeZone(timeZone);
Date finalDate = null;
String date = sdf.format(cal.getTime());
try {
finalDate = sdf.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finalValue = finalDate.getTime();
return finalValue;
}
As given in, above method
while formatting
String date = sdf.format(cal.getTime());
I m getting correct current time in GMT but as i do parsing by following code:
finalDate=sdf.parse(date);
Date got changed from current GMT time to 15:35:16 IST 2013 that is current time of my system.
I tried with Calendar as well in another way:
TimeZone timeZoneGmt=TimeZone.get("GMT");
Calendar calGmt = Calendar.getInstance();
calGmt.setTimeZone(timeZoneGmt);
long finalGmtValue = 0;
finalGmtValue = calGmt.getTimeInMillis();
System.out.println("Date......" + calGmt.getTime());
but still getting date as current time of my System Thu Jan 23 15:58:16 IST 2014 Not getting GMT current time.
You've misunderstood how Date works. A Date doesn't have a time zone - if you use Date.toString() you'll always see the default time zone. The long value in a Date is purely the number of milliseconds since the Unix epoch: it doesn't have any concept of time zone or calendar system.
If you want to represent a date and time in a particular time zone and calendar, use Calendar instead - but for getting "the current date and time as a long" you can just use System.currentTimeMillis(), which again does not have anything to do with the system time zone.
Additionally, even if you did want to do manipulation like this, you shouldn't be using string conversions. You're not conceptually performing any string conversions, so why introduce them?
If your aim is to display (as a string) the current date and time in a particular time zone, you should just use something like:
Date date = new Date(); // This will use the current time
SimpleDateFormat format = new SimpleDateFormat(...); // Pattern and locale
format.setTimeZone(zone); // The zone you want to display in
String formattedText = format.format(date);
When working with date and time APIs - particularly bad ones like the Java Calendar/Date API - it's very important that you understand exactly what each value in your system represents.
I am just starting with Java (Android) and got stuck on a Date formatting issue.
I have a small Form where you can enter a project name and choose a Start date on a Calendar. The Startdate and Projectname gets than entered into the database, after that the pre-defined Tasks get than entered automatically into the database.
Task 1 Due Date is Startdate,
Task 2 is the Startdate plus x days = DueDate2,
Task 3 is The DueDate2 plus x days = DueDate3
I have now come up with the below Sourcecode and everything works besides that I get the wrong Format of my Date. For some reason, my Format is correct in newDateStr, but when I parse it again to be a Date Object, the format changes and is than incorrect. I can't see my mistake, anyone can help?
My understanding is:
Set the Date format of the date entered (curFormat)
Set the target Date format (postFormater)
Parse your Date which is a String at this time, to turn it into a date Object (use curFormat)
Format this date to get target date format (use postFormater), now its a String again
Parse this again to get it back to be a date which is needed for the calendar
Use calendar instance, setTime(here the formated date) and add the x days
Format the Date to get target date format (use postFormater), now its a String again
Because I need a Date Object again, I have to parse it again.
// The format of your input date string
SimpleDateFormat curFormater = new SimpleDateFormat("MM/dd/yyyy");
// The format of your target date string
SimpleDateFormat postFormater = new SimpleDateFormat("dd-MM-yyyy");
// The calendar instance which adds a locale to the date
Calendar cal = Calendar.getInstance();
// Parse the string (pro.getStart()) to return a Date object
Date dateObj = curFormater.parse(pro.getStart());
// Format the Date dd-MM-yyyy
String newDateStr = postFormater.format(dateObj);
// Parse the string to return a Date object
Date Startdate = postFormater.parse(newDateStr);
while (cur.isAfterLast() == false)
{
Integer delayTime = cur.getInt(cur.getColumnIndex("DelayTime"));
if (flag == false)
{
dateInString = Startdate;
flag = true;
}else{
cal.setTime(dateInString);
// add the extra days
cal.add(Calendar.DAY_OF_MONTH, delayTime);
// Format the Date dd-MM-yyyy
newDateStr = postFormater.format(cal.getTime());
// Parse the string to return a Date object
dateInString = postFormater.parse(newDateStr);
Log.i("newDateStr Format",newDateStr.toString()); // 29-11-2012
Log.i("dateInString parse",dateInString.toString()); // Thu Nov 29 00:00:00 GMT 2012
I hope someone sees my mistake. Thank you very much in advance !
A java.util.Date object does not have any format in it or memory of the format you used to parse it. The output of its toString method, and hence what you get as output from dateInString.toString() will always be in the default JDK format that you are seeing: Thu Nov 29 00:00:00 GMT 2012
You have to use a formatter to convert it into a formatted string whenever you want to display it. You cannot "Format the Date object" so to say. (UI frameworks tend to have built in facilities for doing this automatically.)
Don't keep converting the Calendar back to a string each time you loop. Keep one and just accumulate the delays in place...
SimpleDateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
// Set the date once
cal.setTime(fmt.parse(pro.getStart()));
while(!cur.isAfterLast()) {
// Accumulate additional days
Integer delayTime = cur.getInt(cur.getColumnIndex("DelayTime"));
cal.add(Calendar.DAY_OF_MONTH, delayTime);
}
String endDate = fmt.format(cal.getTime());
I want to know whether the Time values of a Calendar object equal the value of a java.sql.Time object.
E.g
Calendar c; //c.getTime().toString() == "Sat Jan 07 09:00:00 GMT 2012"
Time t; //d.toString() == "09:00:00";
I tried
t.equals(c.getTime())
But because the Calendar has Date information the expression is false.
What would be the best way the compare the two?
Edit:
The Time object is retrieve though Hibernate and come with no date information.
The Calendar object is create by
Calendar c= Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 9);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
The way you use is perfectly fine. The goal is unclear, though. Why do you want c to be equal to d?
Additionally, there's no way to have d.toString() == "09:00:00" — Date always have, well, the date included.
What's more important, though, is that Date has no timezone information (well, it used to have, but you're discouraged to touch this part of Date), so you cannot tell 09:00 UTC from 10:00 BST—that is, unless you specify the timezone. You can get the timezone from Calendar c, and it sort of explains what you need to do:
Create a Calendar from your date
Copy timezone from the calendar you already use
Compare the Calendar fields which are of interest for you. I suppose that will be hour, minute, second, and, perhaps, millisecond.
Update: now that you've mentioned it's actually java.sql.Time, I'm worried. The problem is,
SQL servers usually store time as a structure containing hours, minutes, seconds, etc. That is, there's an implied timezone (the SQL Server timezone)
java.sql.Time stores time as milliseconds since "zero epoch" value of January 1, 1970. The date part is usually stripped to January 1, 1970 — but this class does not contain timezone information. (Well, again, it sort of does, but it's deprecated.)
Calendar has an explicitly set timezone
What it means in practice is, that the time from the server gets converted into milliseconds using system default timezone, then you read this value and compare it with a Calendar with its own timezone.
If it sounds confusing and fragile, that's because it is. So basically you have three timezones:
SQL Server TZ
JVM's default TZ
Calendar's TZ
All three must be the same so that any comparison would make any sense.
You can use Date, Calendar, GregorianCalendar,SimpleDateFormat` etc classes to deal with date-time in Java. Let's see some examples.
SimpleDateFormat dayFormat = new SimpleDateFormat("D");
int _currentDay = Integer.parseInt(dayFormat.format(new Date(System.currentTimeMillis())));
SimpleDateFormat monthFormat = new SimpleDateFormat("M");
int _currentMonth = Integer.parseInt(monthFormat.format(new Date(System.currentTimeMillis())));
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
int _currentYear = Integer.parseInt(yearFormat.format(new Date(System.currentTimeMillis())));
System.out.println(_currentDay+"/"+_currentMonth+"/"+_currentYear);
Would display the current date based on the current millisecond.
String toDate = "07/1/2012";
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
Calendar currentDateCal = Calendar.getInstance();
// Zero out the hour, minute, second, and millisecond.
currentDateCal.set(Calendar.HOUR_OF_DAY, 0);
currentDateCal.set(Calendar.MINUTE, 0);
currentDateCal.set(Calendar.SECOND, 0);
currentDateCal.set(Calendar.MILLISECOND, 0);
Date currentDate = currentDateCal.getTime();
Date toDt;
try
{
toDt = df.parse(toDate);
}
catch (ParseException e)
{
toDt = null;
System.out.println(e.getMessage());
}
if (currentDate.equals(toDt))
{
System.out.println(currentDate); // Displays the current date.
//Rest of the stuff.
}
String toDate = "07/12/2012";
try
{
if (new SimpleDateFormat("MM/dd/yyyy").parse(toDate).getTime() / (1000 * 60 * 60 * 24) >= System.currentTimeMillis() / (1000 * 60 * 60 * 24))
{
System.out.println("True");
}
else
{
System.out.println("Untrue");
}
}
catch(ParseException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
String toDateAsString = "07/12/2012";
Date toDate=null;
try
{
toDate = new SimpleDateFormat("MM/dd/yyyy").parse(toDateAsString);
}
catch (ParseException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
long toDateAsTimestamp = toDate.getTime();
long currentTimestamp = System.currentTimeMillis();
long getRidOfTime = 1000 * 60 * 60 * 24;
long toDateAsTimestampWithoutTime = toDateAsTimestamp / getRidOfTime;
long currentTimestampWithoutTime = currentTimestamp / getRidOfTime;
if (toDateAsTimestampWithoutTime >= currentTimestampWithoutTime)
{
System.out.println("True");
}
else
{
System.out.println("False");
}
The JodaTime's variant:
String toDateAsString = "07/01/2012";
DateTime toDate = DateTimeFormat.forPattern("MM/d/yyyy").parseDateTime(toDateAsString);
DateTime now = new DateTime();
if (!toDate.toLocalDate().isBefore(now.toLocalDate()))
{
System.out.println("True");
}
else
{
System.out.println("False");
}
why don't you compare the time in milliseconds?
Date d;
Calendar c;
System.out.println(d.getTime() == c.getTimeInMillis());
Since, you tagged this Question with DateTime, i assume you use Joda already
...
//Initialize Calendar and Date Object
DateTime d1 = new DateTime(c.getTime());
DateTime d2 = new DateTime(d.getTime());
// Convert d1 and d2 to LocalDate say ld1 and ld2 since, Java Date defaults to GMT
ld1.compareTo(ld2);
?
I had to do this today and the answers in this post helped my solve my problem. I know all my timezones are the same like the OPs. And I don't have the liberty to use Joda time in my legacy code so for the benefit of others who have the same conditions, here is how I did it with vanilla Java.
Methodology:
java.sql.Time has a getTime() due to inheritance from
java.util.Date. Using this method, one can create a
java.util.Date object that represents just the time portion since
Java epoch.
For comparison, one must convert the desired java.util.Calendar
object to produce a java.util.Date object that represents another
time since Java epoch.
Since the date parts are now equivalent, any comparison between the 2
objects would only compare the time parts producing the desired result.
Without further adieu, here is the code:
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Test {
/**
* Method to convert a calendar object to java's epoch date
* keeping only the time information
*/
public static Date toEpochDate(Calendar calendar) {
return new Date(Time.valueOf(new SimpleDateFormat("HH:mm:ss").format(calendar.getTime())).getTime());
}
public static void main(String[] args) {
// create any calendar object
Calendar someTime = Calendar.getInstance();
someTime.set(Calendar.HOUR_OF_DAY, 17);
someTime.set(Calendar.MINUTE, 0);
someTime.set(Calendar.SECOND, 0);
// convert it to java epoch date
Date someDate = toEpochDate(someTime);
// create a date object from java.sql.Time
Date fromSqlTime = new Date(Time.valueOf("17:00:00").getTime());
// now do the comparison
System.out.println("Some Date: " + someDate.toString());
System.out.println("Sql Time: " + fromSqlTime.toString());
System.out.println("Are they equal? " + someDate.equals(fromSqlTime));
}
}
The above produces the following output:
Some Date: Thu Jan 01 17:00:00 EST 1970
Sql Time: Thu Jan 01 17:00:00 EST 1970
Are they equal? true
Using the above methodology, and by changing .equals() to .before() or .after(), various time comparison convenience methods can be created.