I have an date object from which i need to getTime(). The issue is it always shows 00:00:00.
SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm:ss");
long date = Utils.getDateObject(DateObject).getTime();
String time = localDateFormat.format(date);
Why is the time always '00:00:00'. Should i append Time to my Date Object
You should pass the actual Date object into format, not a long:
SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm:ss");
String time = localDateFormat.format(Utils.getDateObject(DateObject));
Assuming that whatever Utils.getDateObject(DateObject) is actually returns a Date (which is implied by your question but not actually stated), that should work fine.
For example, this works perfectly:
import java.util.Date;
import java.text.SimpleDateFormat;
public class SDF {
public static final void main(String[] args) {
SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm:ss");
String time = localDateFormat.format(new Date());
System.out.println(time);
}
}
Re your comment below:
Thanks TJ, but actually i am still getting 00:00:00 as time.
That means your Date object has zeroes for hours, minutes, and seconds, like so:
import java.util.Date;
import java.text.SimpleDateFormat;
public class SDF {
public static final void main(String[] args) {
SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm:ss");
String time = localDateFormat.format(new Date(2013, 4, 17)); // <== Only changed line (and using a deprecated API)
System.out.println(time);
}
}
Apart from above solution , you can also use calendar class if you don't have specific requirement
Calendar cal1 =new GregorianCalendar() or Calendar.getInstance();
SimpleDateFormat date_format = new SimpleDateFormat("HH:mm:ss");
System.out.println(date_format.format(cal1.getTime()));
For example, you can use next code:
public static int getNotesIndexByTime(Date aDate){
int ret = 0;
SimpleDateFormat localDateFormat = new SimpleDateFormat("HH");
String sTime = localDateFormat.format(aDate);
int iTime = Integer.parseInt(sTime);
return iTime;// count of hours 0-23
}
Related
Experts,
I would like to get current datetime in a given timezone for global usage.
So,
I create a class like below, but it shows syntax error for the df.setTimeZone statement. What is the neat way to achieve this? More specific, I would like to set timezone property for a class member rather than a local variable.
I defined many date format through SimpleDateFormat, how to specify a timezone for all of them? (.setTimeZone seems only for one date format) Thanks.
public class Global {
static SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setTimeZone(TimeZone.getTimeZone("GIVEN_TIMEZONE"));
static String strDate = df.format(new Date());
}
If you absolutely must do it with static fields, you need the code to be in a static initializer block:
class Global {
static SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
static {
df.setTimeZone(TimeZone.getTimeZone("GIVEN_TIMEZONE"));
}
static String strDate = df.format(new Date());
}
UPDATE
If you have lot of dates to do like that, with different date formats and/or time zones, it may be better to use a helper method.
class Global {
static String strDate = format(new Date(), "dd/MM/yyyy", "GIVEN_TIMEZONE");
private static String format(Date date, String format, String timeZoneID) {
SimpleDateFormat df = new SimpleDateFormat(format);
df.setTimeZone(TimeZone.getTimeZone(timeZoneID));
return df.format(date);
}
}
Please try in below possible syntax:
String dtc = "2014-04-02T07:59:02.111Z";
SimpleDateFormat readDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
readDate.setTimeZone(TimeZone.getTimeZone("GMT")); // Important line
Date date = readDate.parse(dtc);
SimpleDateFormat writeDate = new SimpleDateFormat("dd.MM.yyyy, HH.mm");
writeDate.setTimeZone(TimeZone.getTimeZone("GMT+04:00")); // Important line
String s = writeDate.format(date);
You need to import below class:
https://developer.android.com/reference/java/util/TimeZone.html
I am parsing the date as:
public class Consts{
public static final SimpleDateFormat DATE_FORMATTER_WITHOUT_TIME_ZONE = new SimpleDateFormat(
"yyyy-MM-dd HH:mm");
public static final SimpleDateFormat DATE_FORMATTER_2 = new SimpleDateFormat(
"MM-dd-yyyy HH:mm:ss ZZZZ");
}
cDate = new GregorianCalendar();
sDate = new GregorianCalendar();
eDate = new GregorianCalendar();
if (mStartTimeTV.getText().toString().equals("Now")) {
sDate.setTime(cDate.getTime());
} else {
sDate.setTime(Consts.DATE_FORMATTER_WITHOUT_TIME_ZONE
.parse(mStartTimeTV.getText().toString()));
}
if (!mEndTimeTV.getText().toString().equals("")) {
eDate.setTime(Consts.DATE_FORMATTER_WITHOUT_TIME_ZONE
.parse(mEndTimeTV.getText().toString()));
} else {
eDate.setTime(sDate.getTime());
// eDate = sDate;
}
And then i format the date as below before sending it to the server.:
request.addProperty("StartTime",
Consts.DATE_FORMATTER_2.format(sDate.getTime()));
request.addProperty("EndTime",
Consts.DATE_FORMATTER_2.format(eDate.getTime()));
But the thing is that on devices running 4.1.2 it is sending the date as:
Start Date: 03-23-2015 21:17:20 +0500
End Date : 10-23-2015 21:15:00 +0500
which throws exception on the server side.
But on the other devices it is sending dates as:
Start Date: 03-23-2015 21:12:13 GMT+05:00
End Date : 03-23-2015 21:16:00 GMT+05:00
which is required.
Am i doing something wrong? How can i prevent this problem so that all devices sends the same dates. (for example 03-23-2015 21:16:00 GMT+05:00)
The difference is caused by different locales set up on devices.
To mitigate the locale differences, you should use particular locale while formatting the date string. Here is a sample from my code, solving the same issue:
new SimpleDateFormat(C.FORMAT_DATETIMEZ, Locale.US).format(new Date(time))
You can extend SimpleDateFormat and override its format(...) function as following:
public class ExSimpleDateFormat extends SimpleDateFormat{
private static final long serialVersionUID = -8275126788734707527L;
public ExSimpleDateFormat() {
super();
}
public ExSimpleDateFormat(String string, Locale us) {
super(string, us);
}
#Override
public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition pos)
{
final StringBuffer buf = super.format(date, toAppendTo, pos);
buf.insert(buf.length() - 2, ':');
return buf;
};
}
And execute following code:
Calendar ca = Calendar.getInstance();
ca.setTimeInMillis(System.currentTimeMillis());
ExSimpleDateFormat exSimpleDateFormat = new ExSimpleDateFormat("dd-MM-yyyy HH:mm:ss 'GMT'Z", Locale.US);
exSimpleDateFormat.setTimeZone(ca.getTimeZone()); //your device timezone which can be GMT+xx:yy or GMT-xx:yy
String desiredTime = exSimpleDateFormat.format(ca.getTime());
Output would be like: 23-03-2015 23:12:52 GMT+05:00
Let me know if it helps.
Thanks
Given a date D, I am trying to create two Calendar instances for that day at the following UTC times: 00:00:00 and 23:59:59. My algorithm should work regardless of my timezone (mine is UTC+1) and, given the day of D, for that D the time has to be set.
This is my code:
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
private static void f(Date date) {
Calendar c1 = Calendar.getInstance();
c1.setTime(date);
c1.set(Calendar.HOUR_OF_DAY, 0);
c1.set(Calendar.MINUTE, 0);
c1.set(Calendar.SECOND, 0);
Calendar c2 = Calendar.getInstance();
c2.setTime(date);
c2.set(Calendar.HOUR_OF_DAY, 23);
c2.set(Calendar.MINUTE, 59);
c2.set(Calendar.SECOND, 59);
//...
Then, I am trying to transform them into a UTC string with this code:
//...
String sc1 = fromDateToUTCString(c1.getTime());
String sc2 = fromDateToUTCString(c2.getTime());
System.out.println(sc1);
System.out.println(sc2);
}
public static String fromDateToUTCString(final Date date) {
final String ISO_FORMAT = "yyy-MM-dd'T'HH:mm:ss'Z'";
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT);
final TimeZone utc = TimeZone.getTimeZone("UTC");
sdf.setTimeZone(utc);
return sdf.format(date);
}
After this, the console prints 11:00:13 for c1 and 22:59:13 for c2.
JDK7.
The test main is trivial:
public static void main(String[] args) {
f(new Date());
}
Why?
I'm not sure what is your intention, but below code gives what you expect as the output.
...
Calendar c1 = Calendar.getInstance();
c1.setTimeInMillis(date.getTime());
c1.add(Calendar.HOUR_OF_DAY, -1*c1.get(Calendar.HOUR_OF_DAY));
c1.add(Calendar.MINUTE, -1*c1.get(Calendar.MINUTE));
c1.add(Calendar.SECOND, -1*c1.get(Calendar.SECOND));
Calendar c2 = Calendar.getInstance();
c2.setTimeInMillis(date.getTime());
c2.add(Calendar.HOUR, -1*c2.get(Calendar.HOUR_OF_DAY) + 23);
c2.add(Calendar.MINUTE, -1*c2.get(Calendar.MINUTE) + 59);
c2.add(Calendar.SECOND, -1*c2.get(Calendar.SECOND) + 59);
....
//comment the time zone setting
//sdf.setTimeZone(utc);
Output:
2015-01-21T 00:00:00Z
2015-01-21T 23:59:59Z
There is a Z at the end because of the format you have used. But actually the output is not in UTC.
Update:
With your code:
2015-01-20T16:30:00Z
2015-01-21T16:29:59Z
With your code + -Duser.timezone=GMT adding to JVM:
2015-01-21T00:00:00Z
2015-01-21T23:59:59Z
I assume you are not in UTC, so you're creating a time for timezone X and convert it to UTC afterwards. The solution is to create the Calendar objects in UTC:
c1.setTimeZone(TimeZone.getTimeZone("UTC"));
respectively
c2.setTimeZone(TimeZone.getTimeZone("UTC"));
Complete Sample Program
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class CalendarTest {
public static void main(String[] args) {
f(new Date());
}
private static void f(Date date) {
Calendar c1 = Calendar.getInstance();
c1.setTime(date);
c1.set(Calendar.HOUR_OF_DAY, 0);
c1.set(Calendar.MINUTE, 0);
c1.set(Calendar.SECOND, 0);
c1.setTimeZone(TimeZone.getTimeZone("UTC"));
Calendar c2 = Calendar.getInstance();
c2.setTime(date);
c2.set(Calendar.HOUR_OF_DAY, 23);
c2.set(Calendar.MINUTE, 59);
c2.set(Calendar.SECOND, 59);
c2.setTimeZone(TimeZone.getTimeZone("UTC"));
String sc1 = fromDateToUTCString(c1.getTime());
String sc2 = fromDateToUTCString(c2.getTime());
System.out.println(sc1);
System.out.println(sc2);
}
public static String fromDateToUTCString(final Date date) {
final String ISO_FORMAT = "yyy-MM-dd'T'HH:mm:ss'Z'";
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT);
final TimeZone utc = TimeZone.getTimeZone("UTC");
sdf.setTimeZone(utc);
return sdf.format(date);
}
}
leads to
2015-01-21T00:00:00Z
2015-01-21T23:59:59Z
I downloaded joda library and extract joda time to calculate time difference,
Here is my class that calculate date difference: (I'm using Java 1.7)
public class TimeDiffereneceTest {
static String secondDate,firstDate, dateDifference;
public static void main(String[] args) {
firstDate = "2014/07/20";
secondDate = getTodayDate(); // Generate 2014/07/23
DateDifference(firstDate, secondDate);
}
public static String getTodayDate() {
Calendar todayDate = Calendar.getInstance();
SimpleDateFormat simpleFormat = new SimpleDateFormat("YYYY/MM/dd");
String strDate = simpleFormat.format(todayDate.getTime());
return strDate;
}
public static void DateDifference(String firstDate,String nowDate) {
Date d1=null;
Date d2=null;
SimpleDateFormat format = new SimpleDateFormat("YYYY/MM/dd");
try{
d1 = format.parse(firstDate);
d1 = format.parse(nowDate);
DateTime dt1 = new DateTime(d1);
DateTime dt2 = new DateTime(d2);
System.out.println("Day difference is: "+Days.daysBetween(dt1, dt2).getDays()); // 206!
}
catch(Exception e){
e.printStackTrace();
}
}
}
The result should be 3 because today date is 2014/07/23 and first date was "2014/07/20" , But has wrong result (206).
I see some problems with code :
1) new SimpleDateFormat should throw illegal argument becouse of "YYYY" should be"yyyy" (at least for me this works
2) In DateDifference (should be name dateDifference since its a method, not class - naming convenction)
You got
d1 = format.parse(firstDate);
d1 = format.parse(nowDate);
Instead of
d1 = simpleFormat.parse(firstDate);
d2 = simpleFormat.parse(nowDate);
Try using this code, it works for me.
public class TimeDiffereneceTest {
static String secondDate,firstDate, dateDifference;
static SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy/MM/dd");
public static void main(String[] args) {
firstDate = "2014/07/20";
secondDate = getTodayDate(); // Generate 2014/07/23
DateDifference(firstDate, secondDate);
}
public static String getTodayDate() {
Calendar todayDate = Calendar.getInstance();
String strDate = simpleFormat.format(todayDate.getTime());
return strDate;
}
public static void DateDifference(String firstDate,String nowDate) {
Date d1=null;
Date d2=null;
try{
d1 = simpleFormat.parse(firstDate);
d2 = simpleFormat.parse(nowDate);
DateTime dt1 = new DateTime(d1);
DateTime dt2 = new DateTime(d2);
System.out.println("Day difference is: "+Days.daysBetween(dt1, dt2).getDays()); // 206!
}
catch(Exception e){
e.printStackTrace();
}
}
}
Which java version are you using?
In 7, capital Y has a different meaning from y. In 6 Y is not specified so it throws the following exception:
java.lang.IllegalArgumentException: Illegal pattern character 'Y'
Your code has two issues that I can see (apart from the random unused statics).
Y is not the format code for year, y is.
d2 is null, you are parsing both strings into d1.
The following code gives me 4 when run today, '2014/07/24'.
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
String firstDate = "2014/07/20";
String secondDate = format.format(new Date());
int days = Days.daysBetween(new DateTime(format.parse(firstDate)), new DateTime(format.parse(secondDate))).getDays();
System.out.println(days);
I have table with data of date.
This is how I calcaulted the date
DateFormat dateFormat = getFormat();
date = dateFormat.parse((String) value).getTime();
if(date != null) {
cell.setValue(dateFormat.format(date));
tableViewer.update(element, null);
}
public static DateFormat getFormat() {
String systemLocale = System.getProperty("user.language"); //$NON-NLS-1$
Locale locale = new Locale(systemLocale);
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
return dateFormat;
}
The date is exist in the screen in format Month(name of the month) date, year
for example Apr 26,2014.
Now I want to get the value of the cell and to get to format of 'yyyy-mm-dd'
The value of the date is Apr 26,2014.
How I can get the result of 2014-04-26 ? also I think that the value in the UI could change according to the localization of the user
I tried
DateFormat dateFormat = getFormat();
Date parse = dateFormat.parse((String) key);
but then all the get method are deprecated and also I didn't get right result for getYear
I am not expert in the date maybe I miss something
Try this:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class CustomFormattedDate {
public static void main(String[] args) {
Date date = new Date();
// if you use DD for Daypattern, you'll get the day of the year, e.g. 119 for the
// 29th April 2014, if you want 29, the day of the month, use dd
SimpleDateFormat df = new SimpleDateFormat("YYYY-dd-MMM", new Locale(System.getProperty("user.language")));
System.out.println(df.format(date));
System.out.println(getDateFormat().format(date));
}
}
Output
2014-29-Apr