I have a weird problem I used Java to get a current date but I am getting different results on several devices, on one correct & on another wrong.
Here is my code:
public String getCurrentDate() {
/// get date
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
Date date = new Date();
System.out.println(dateFormat.format(date)); //2017-11-13 18:20:46 correct time is 11am
return dateFormat.format(date);
}
On the device that gives the wrong result I set automatic time zone use network-provided time zone & time of the device is correct.
Are testing with real devices?
You can also try the Calendar Class that are from Android. for more info visit (https://developer.android.com/reference/java/util/Calendar.html)
Check the Example bellow:
Calendar current_time_cal = Calendar.getInstance();
current_time_cal.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
int hours = current_time.get(Calendar.HOUR);
int current_am_pm = current_time.get(Calendar.AM_PM);
current_time_cal.set(Calendar.HOUR_OF_DAY, (hours == 0)? 12 : hours);
current_time_cal.set(Calendar.MINUTE, current_time.get(Calendar.MINUTE));
current_time_cal.set(Calendar.SECOND, 0);
Try this:
Calendar c = Calendar.getInstance();
System.out.println("Current time: " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
You can use this method to get current time from your device:
public String getCurrentDate() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
String date = sdf.format(calendar.getTime());
return date;
}
This method will return current date as string.
Related
I want to increment the date by one. I have the below code while running the code I am getting unparseable date finally I want the date as string in the format of MM-DD-YYYY.
But same program is working with the YYYY-MM-DD format but i want mydate in this format(MM-DD-YYYY)
String dt = schReq.getStartDate(); // Start date
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, days); // number of days to add
dt = sdf.format(c.getTime());
schReq.setStartDate(dt);
Can anyone please help me?
The code should be working fine as long as dt and days are correct. This gave me 12-18-2014:
String dt = "12-17-2014"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime());
You have to use two different DateFormats:
one for parsing the string and one for formatting.
String dt = schReq.getStartDate(); // Start date
SimpleDateFormat sdf_parser = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf_parser.parse(dt));
c.add(Calendar.DATE, days); // number of days to add
dt = sdf.format(c.getTime());
schReq.setStartDate(dt);
Here is my code.
public String getDateTime()
{
String dateAndTime =
(new SimpleDateFormat("hh:mm aaa")).format(new Date());
return dateAndTime;
}
public String getDate()
{
android.text.format.DateFormat df = new android.text.format.DateFormat();
String Date = df.format("MM-dd-yyyy", new java.util.Date()).toString();
return Date;
}
I have searched about this. but, i cant find the perfect answer. Please help me.
You can use the below function
private Date shiftTimeZone(Date date, TimeZone sourceTimeZone, TimeZone targetTimeZone) {
Calendar sourceCalendar = Calendar.getInstance();
sourceCalendar.setTime(date);
sourceCalendar.setTimeZone(sourceTimeZone);
Calendar targetCalendar = Calendar.getInstance();
for (int field : new int[] {Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND}) {
targetCalendar.set(field, sourceCalendar.get(field));
}
targetCalendar.setTimeZone(targetTimeZone);
System.out.println("........"+targetCalendar.getTimeZone());
return targetCalendar.getTime();
}
Usage:
Date date= new Date();
SimpleDateFormat sf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sf.format(date);
TimeZone tz = TimeZone.getTimeZone("GMT") OR TimeZone tz = sf.getTimeZone();
TimeZone tz1 = TimeZone.getTimeZone("EST");
Date c= shiftTimeZone( date,tz,tz1);
System.out.println("Format : " + sf.format(c));
Output
sun.util.calendar.ZoneInfo[id="EST",offset=-18000000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Format : 01-05-2013 16:23:57
You can find your answer here :
Date and time conversion to some other Timezone in java
You have to use TimeZone class and Calendar class.
Get current time :
Calendar currentdatetime = Calendar.getInstance();
Just pass your time zone name in TimeZone class like this :
TimeZone.getTimeZone("EST");
Use DateFormater
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Then format your time like this :
formatter.setTimeZone(obj);
and get output like this :
System.out.println("EST Time is : "+ formatter.format(currentdatetime .getTime())
This question already has answers here:
How to check if a date Object equals yesterday?
(9 answers)
Closed 8 years ago.
The following function produces today's date; how can I make it produce only yesterday's date?
private String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date).toString();
}
This is the output:
2012-07-10
I only need yesterday's date like below. Is it possible to do this in my function?
2012-07-09
Update
There has been recent improvements in datetime API with JSR-310.
Instant now = Instant.now();
Instant yesterday = now.minus(1, ChronoUnit.DAYS);
System.out.println(now);
System.out.println(yesterday);
https://ideone.com/91M1eU
Outdated answer
You are subtracting the wrong number:
Use Calendar instead:
private Date yesterday() {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return cal.getTime();
}
Then, modify your method to the following:
private String getYesterdayDateString() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return dateFormat.format(yesterday());
}
See
IDEOne Demo
You can do following:
private Date getMeYesterday(){
return new Date(System.currentTimeMillis()-24*60*60*1000);
}
Note: if you want further backward date multiply number of day with 24*60*60*1000 for example:
private Date getPreviousWeekDate(){
return new Date(System.currentTimeMillis()-7*24*60*60*1000);
}
Similarly, you can get future date by adding the value to System.currentTimeMillis(), for example:
private Date getMeTomorrow(){
return new Date(System.currentTimeMillis()+24*60*60*1000);
}
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
Use Calender Api
Try this one:
private String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Create a calendar object with today date. Calendar is in java.util pakage.
Calendar calendar = Calendar.getInstance();
// Move calendar to yesterday
calendar.add(Calendar.DATE, -1);
// Get current date of calendar which point to the yesterday now
Date yesterday = calendar.getTime();
return dateFormat.format(yesterday).toString();
}
Try this;
public String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return dateFormat.format(cal.getTime());
}
changed from your code :
private String toDate(long timestamp) {
Date date = new Date (timestamp * 1000 - 24 * 60 * 60 * 1000);
return new SimpleDateFormat("yyyy-MM-dd").format(date).toString();
}
but you do better using calendar.
There is no direct function to get yesterday's date.
To get yesterday's date, you need to use Calendar by subtracting -1.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
I'm facing some problems in comparing the current date and the date which is retrieved from Database.I just retrieved date from DataBase and Stored in a Date variable like this
String due_date_task = cursor.getString(cursor.getColumnIndex(dueDateOfTask));
SimpleDateFormat currentFormater = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = currentFormater.parse(due_date_task);
Now,what i want is should check whether date which is retrieved from DataBase is Equivalent to CurrentDate or not.
Calendar currentDate = Calendar.getInstance();
Date date2 = currentDate.getTime();
if(date1.equals(date2))
System.out.println("Today Task");
i just want to check like this.Thanks in advance
For exact match including milliseconds, use getTime:
if(date.getTime() == date1.getTime()){
//do something
}
You can use this function:
private boolean compareDates(Calendar objCal1, Calendar objCal2) {
return ((objCal1.get(Calendar.YEAR) == objCal2.get(Calendar.YEAR))
&& (objCal1.get(Calendar.DAY_OF_YEAR) == objCal2.get(Calendar.DAY_OF_YEAR)));
}
creating the calendar objects:
Calendar objCal1 = new GregorianCalendar().setTime(date);
Calendar objCal2 = new GregorianCalendar().setTime(date1);
Try this way to get the current date,
Calendar calCurr = Calendar.getInstance();
Log.i("Time in mili of Current - Normal", ""+calCurr.getTimeInMillis()); // see what it gives? dont know why?
Date date = new Date();
calCurr.set(date.getYear()+1900, date.getMonth()+1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());// so added one month to it
Log.i("Time in mili of Current - after update", ""+calCurr.getTimeInMillis()); // now get correct
now create Calendar object for database value,
String due_date_task = cursor.getString(cursor.getColumnIndex(dueDateOfTask));
SimpleDateFormat currentFormater = new SimpleDateFormat("dd/MM/yyyy");
Date date = currentFormater.parse(due_date_task);
Calendar start = Calendar.getInstance();
start.set(date.getYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
and now Compare both the Calendar objects
if(calCurr.equals(start))
I know about to get the date in android with the help of the calender instance.
Calendar c = Calendar.getInstance();
System.out.println("====================Date is:"+ c.get(Calendar.DATE));
But with that i got only the number of the Date. . .
In My Application i have to do Some Calculation based on the Date Formate. Thus if the months get changed then that calculation will be getting wrong.
So for that reason i want the full date that gives the Month, Year and the date of the current date.
And what should be done if i want to do Some Calculation based on that date ?
As like: if the date is less then two weeks then the message should be printed. . .
Please Guide me in this.
Thanks.
Look at here,
Date cal=Calendar.getInstance().getTime();
String date = SimpleDateFormat.getDateInstance().format(cal);
for full date format look SimpleDateFormat
and IF you want to do calculation on date instance I think you should use, Calendar.getTimeInMillis() field on these milliseconds make calculation.
EDIT: these are the formats by SImpleDateFormat class.
String[] formats = new String[] {
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mmZ",
"yyyy-MM-dd HH:mm:ss.SSSZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
};
for (String format : formats) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
}
EDIT: two date difference (Edited on Date:09/21/2011)
String startTime = "2011-09-19 15:00:23"; // this is your date to compare with current date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = dateFormat.parse(startTime);
// here I make the changes.... now Date d use a calendar's date
Date d = Calendar.getInstance().getTime(); // here you can use calendar beco'z date is now deprecated ..
String systemTime =(String) DateFormat.format("yyyy-MM-dd HH:mm:ss", d.getTime());
SimpleDateFormat df1;
long diff = (d.getTime() - date1.getTime()) / (1000);
int Totalmin =(int) diff / 60;
int hours= Totalmin/60;
int day= hours/24;
int min = Totalmin % 60;
int second =(int) diff % 60;
if(day < 14)
{
// your stuff here ...
Log.e("The day is within two weeks");
}
else
{
Log.e("The day is more then two weeks");
}
Thanks.
Use SimpleDateFormat class,
String date = SimpleDateFormat.getDateInstance().format(new Date());
you can use
//try different flags for the last parameter
DateUtils.formatDateTime(context,System.currentTimeMillis(),DateUtils.FORMAT_SHOW_DATE);
for all options check http://developer.android.com/reference/android/text/format/DateUtils.html
try this,
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
int day = c.get(Calendar.DAY_OF_MONTH);
System.out.println("Current date : "
+ day + "/" + (month + 1) + "/" + year);
}
I'm using following methods to get date and time. You can change the locale here to arabic or wot ever u wish to get date in specific language.
public static String getDate(){
String strDate;
Locale locale = Locale.US;
Date date = new Date();
strDate = DateFormat.getDateInstance(DateFormat.DEFAULT, locale).format(date);
return strDate;
}
public static String getTime(){
String strTime;
Locale locale = Locale.US;
Date date = new Date();
strTime = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale).format(date);
return strTime;
}
you can get the value and save it on String as below
String Date= getDate();
String Time = getTime();