I am trying to convert millisecond time value to UTC 12 hour format using following code:
public void updateDateAndTimeForMumbai(String value) {
SimpleDateFormat outputTimeFormatter = new SimpleDateFormat("h:mm");
SimpleDateFormat outputDateFormatter = new SimpleDateFormat("dd/MM/yyyy");
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
try {
calendar.setTimeInMillis(Long.parseLong(value));
Log.i("Scheduled date: " + outputDateFormatter.format(calendar.getTime()));
Log.i("Scheduled time: " + outputTimeFormatter.format(calendar.getTime()));
Log.i("Scheduled time Am/Pm: " + new SimpleDateFormat("aa").format(calendar.getTime()));
} catch (NumberFormatException n) {
//do nothing and leave all fields as is
}
}
Here value = "1479633900000"
Output is:
Scheduled date: 20/11/2016
Scheduled time: 2:55
Scheduled time Am/Pm: AM
What I want is:
Scheduled date: 20/11/2016
Scheduled time: 9:25
Scheduled time Am/Pm: AM
I don't know where is the problem.
You need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.
outputDateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Call this after you do :
SimpleDateFormat outputDateFormatter = new SimpleDateFormat("dd/MM/yyyy");
If the time you are receiving from server is not UTC time, then you shouldn't set your Calendar instance to UTC. but just directly set your Calendar time.
Remove
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
And call
Calendar calendar = Calendar.getInstance();
Here is how should look your final code :
public void updateDateAndTimeForMumbai(String value) {
SimpleDateFormat outputTimeFormatter = new SimpleDateFormat("h:mm");
outputTimeFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat outputDateFormatter = new SimpleDateFormat("dd/MM/yyyy");
outputDateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
try {
calendar.setTimeInMillis(Long.parseLong(value));
Log.i("Scheduled date: " + outputDateFormatter.format(calendar.getTime()));
Log.i("Scheduled time: " + outputTimeFormatter.format(calendar.getTime()));
Log.i("Scheduled time Am/Pm: " + new SimpleDateFormat("aa").format(calendar.getTime()));
} catch (NumberFormatException n) {
//do nothing and leave all fields as is
}
}
Related
I know this Questions Asked before so many time but i didn't get solution from it.
I am trying to convert Datetime to UTC-0.
I have backend as microsoft sharepoint O365.
I am adding record in sharepoint List.
I am store user timezone when it register. so now whenever user login they can see all data with dateandtime in their selected timezone which store at time of registration.
Now my point is user registered timezone is Asia/Kolkata.
now if he login using other country device like London. then he can see all data date time in Asia/Kolkata which is selected at register time.
For eg. User registered timezone at time of registration like GMT+5:30 then if user mobile timezone is whatever they can see in GMT+5:30 DateTime
And if he add any data from app then it also store as Asia/Kolkata timezone which Datetime not as current mobile timezone if he using Mobile in london.
how to Resolve it?
my code like below:
public String getDateAndTimeToUserFormat()
{
String date;
TimeZone timeZone = TimeZone.getTimeZone("Indian Standard Time");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat(serverdateFormat, Locale.US);
simpleDateFormat.setTimeZone(timeZone);
date= simpleDateFormat.format(calendar.getTime());
Log.i("TAG","UserTimezone=>"+this.timeZone);
Log.i("TAG","Time zone: " + timeZone.getID());
Log.i("TAG","default time zone: " + TimeZone.getDefault());
Log.i("TAG","default time : " + Calendar.getInstance().getTime());
Log.i("TAG","UTC: " + date);
Log.i("TAG","Default: " + calendar.getTime());
return date;
}
Output:
UserTimezone=>India Standard Time
Time zone: GMT
default time zone: Africa/Casablanca
default time : Fri Jun 17 12:53:55 GMT+00:00 2016
UTC: 2016-06-17T12:53:55Z
Default: Fri Jun 17 12:53:55 GMT+00:00 2016
finally i have make code for my requirement.
public String getDateTimeToUTC() {
String result=convertToUTCDateTime(convertToUserDateTime(this.timeZone));
return result;
}
/**
*
* #param userTimeZone : is contain String Of User Selected TimeZone
* #return Date: it contain DateTime of UserSelected TimeZone
*/
public Date convertToUserDateTime(String userTimeZone)
{ Date parsed = null;
TimeZone timeZone = TimeZone.getTimeZone(userTimeZone);
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat(serverdateFormat, Locale.US);
simpleDateFormat.setTimeZone(timeZone);
String date = simpleDateFormat.format(calendar.getTime());
try {
parsed=simpleDateFormat.parse(date);
Log.i("TAG", "default time zone: " + TimeZone.getDefault().getID());
Log.i("TAG", "User Selected Timezone=>" + timeZone.getID());
Log.i("TAG", "default Device DateTime : " + Calendar.getInstance().getTime());
Log.i("TAG","User selected DateTime=>"+date);
} catch (ParseException e) {
e.printStackTrace();
}
return parsed ;
} /**
* #param userZoneDateTime : is contain User Selected TimeZone Date
* #return String : Return UTC-0 DateTime String From User Selected DateTimeZone
*/
public String convertToUTCDateTime(Date userZoneDateTime)
{
String result;
TimeZone timeZone1 = TimeZone.getTimeZone("UTC");
SimpleDateFormat simpleDateFormat1 =
new SimpleDateFormat(serverdateFormat, Locale.US);
simpleDateFormat1.setTimeZone(timeZone1);
result = simpleDateFormat1.format(userZoneDateTime);
Log.i("TAG", "UTC Time zone: " + timeZone1.getID());
Log.i("TAG", "UTC: " + result);
return result;
}
I am converting a timestamp into date and time and setting the result on a textview.
For example 1443884578 is Sat 3 October 2015 18:02
I would like to set the above date and time into an alarm manager.After research i found a code that uses a date time picker.
public void onDateSelectedButtonClick(View v) {
// Get the date from our datepicker
int day = picker.getDayOfMonth();
int month = picker.getMonth();
int year = picker.getYear();
// Create a new calendar set to the date chosen
// we set the time to midnight (i.e. the first minute of that day)
Calendar c = Calendar.getInstance();
c.set(year, month, day);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
// Ask our service to set an alarm for that date, this activity talks to the client that talks to the service
scheduleClient.setAlarmForNotification(c);
// Notify the user what they just did
Toast.makeText(this, "Notification set for: " + day + "/" + (month + 1) + "/" + year, Toast.LENGTH_SHORT).show();
}
However its getting only the date and fires the alarm the minute the date occurs.
PROBLEM: I would like to get the date and time from my textview and skip this date time picker in the format i have. Is this possible?
String input = "Sat October 3 2015 18:02"; // Instead of String input = "Mon Feb 06 2015";
Calendar cal = Calendar.getInstance();
Date date = new Date();
// Changed the format to represent time of day
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss", Locale.ENGLISH);
try {
date = sdf.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
cal.setTime(date);
//We haven't parsed the seconds from the original date so this will result
//in 18:02:00 - 10seconds.
//For a correct calculation, you could parse the seconds as well
//See SimpleDateFormat above, but you would have to provide the original date
//with seconds as well
cal.add(Calendar.SECOND, -10);
scheduleClient.setAlarmForNotification(cal);
I want to convert calendar object to date as follow.
int year,month,day;
mCalendarEnd = Calendar.getInstance();
year = mCalendarEnd.get(Calendar.YEAR);
month = mCalendarEnd.get(Calendar.MONTH)+1;
day = mCalendarEnd.get(Calendar.DAY_OF_MONTH);
Now convert it to date object
Date d1 = new Date(day,month,year);
when I print date object:
System.out.println("Date : "+d1.getDay()+"/"+d1.getMonth()+"/"+d1.getYear());
it should print current date but in above code it prints the wrong date. Any idea how can I solve this problem? your all suggestion are appreciable.
You need to do it like this
//Set calendar
Calendar calendar = Calendar.getInstance();
Date date1 = calendar.getTime(); // gives a date object
//To get day difference, Just an example
calendar.add(Calendar.DAY_OF_MONTH, -7);
Date date2 = calendar.getTime(); // gives a date object
long differenceInMillis = Date1.getTime() - Date2.getTime();
long differenceInDays = TimeUnit.DAYS.convert(differenceInMillis, TimeUnit.MILLISECONDS);
Or No need of date objects
Calendar calendar = Calendar.getInstance();
long date1InMillis = calendar.getTimeInMillis();
calendar.add(Calendar.DAY_OF_MONTH, -7);
long date2InMillis = calendar.getTimeInMillis();
long differenceInMillis = date1InMillis - date2InMillis;
long differenceInDays = TimeUnit.DAYS.convert(differenceInMillis, TimeUnit.MILLISECONDS);
calendar.getTimeInMillis()
calendar.getTime() returns Date object.
but if you just need today date new Date() returns today date as Date object, too.
Calendar example:
Calendar calendar = Calendar.getInstance()
Log.i("My Tag", "calendar getTime -----> " + calendar.getTime());
Output:
My Tag: calendar getTime -----> Wed Dec 05 13:03:43 GMT+03:30 2018
Date Example:
Log.i("My Tag", "new Date -----> " + new Date());
Output:
My Tag: new Date -----> Wed Dec 05 13:05:38 GMT+03:30 2018
as you see both of them have the same output.
Why you don't use just the calendar?
System.out.println("Date : " + day + "/" + month + "/" + year);
result 1/1/1900
or you want other format? but dont increment the month with 1
System.out.println("Date : " + day + "/" + new DateFormatSymbols().getMonths()[month] + "/" + year);
result 1/January/1900
Put this in your code:
Date d1 = new Date(year, month, day);
System.out.println("Date : " + d1.getDate() + "/" +d1.getMonth() + "/" + d1.getYear());
you will get the correct date.
d1=new Date(year, month, day);
System.out.println("Dt:"+d1.getDate()+"/"+d1.getMonth()+"/"+d1.getYear());
I have a start date (day, month, year) and need the date say 4 weeks from that date. How can I calculate that? I know how to find the difference between two dates using Calendar so I assume I'm not too far from the answer... Thank you!!!
edit:
This is the final code I wound up using. It returns a String whose value is a date span formatted "MM/dd/YYYY - MM/dd/YYYY"
#SuppressLint("SimpleDateFormat")
private String getSessionDate(int position) {
MySession ms = mSessionList.get(position);
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Calendar calendar = Calendar.getInstance();
calendar.set(ms.getStartYear(), ms.getStartMonth(), ms.getStartDay());
Date startDate = calendar.getTime();
String durationString = ms.getDurationString(); // Format is "## weeks"
int i = 0;
while (Character.isDigit(durationString.charAt(i))) {
i++;
}
int weeks = Integer.parseInt(durationString.substring(0, i));
calendar.add(Calendar.WEEK_OF_YEAR, weeks);
return (format.format(startDate) + " - " + format.format(calendar.getTime()));
}
You can use Calender instance for that.
Calendar calendar = Calendar.getInstance();
calendar.setTime(currentdate);
calendar.add(Calendar.DAY_OF_YEAR, no_of_days)
Date newDate = calendar.getTime();
You can calculate the date by adding or subtracting the no of days
Example :
Get date after 1 week
calendar.add(Calendar.DAY_OF_YEAR, 7);
Get date before 1 week
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date date=null;
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = originalFormat.parse(strDate); // strDate is your date from which you want to get date after 4 weeks
} catch (Exception e) {
e.printStackTrace();
}
long timeFor4week=4*7*24 * 60 * 60 * 1000; /// here 24*60*60*1000 =24 hours i.e 1 day
long timeAfter4week=date.getTime()+timeFor4week;
String finalDateString=originalFormat.format(new Date(timeAfter4week));
So you can get day after 4 weeks.
I am trying to fetch the date 7days prior to today's date.
I am using SimpleDateFormat to fetch today's date.
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
Please guide me through this
Updated answer which I found most useful
SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
String currentDateandTime = sdf.format(new Date());
Date cdate=sdf.parse(currentDateandTime);
Calendar now2= Calendar.getInstance();
now2.add(Calendar.DATE, -7);
String beforedate=now2.get(Calendar.DATE)+"/"+(now2.get(Calendar.MONTH) + 1)+"/"+now2.get(Calendar.YEAR);
Date BeforeDate1=sdf.parse(beforedate);
cdate.compareTo(BeforeDate1);
Thank you for you reply
Use java.util.Calendar, set it to today's date and then subtract 7 days.
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DAY_OF_YEAR, -7);
Date 7daysBeforeDate = cal.getTime();
Edit: In Java 8 it can be done much easier by using classes from java.time package:
final LocalDate date = LocalDate.now();
final LocalDate dateMinus7Days = date.minusDays(7);
//Format and display date
final String formattedDate = dateMinus7Days.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(formattedDate);
You can try out this,
import java.util.Calendar;
public class AddDaysToCurrentDate {
public static void main(String[] args) {
//create Calendar instance
Calendar now = Calendar.getInstance();
System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
//add days to current date using Calendar.add method
now.add(Calendar.DATE,1);
System.out.println("date after one day : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
//substract days from current date using Calendar.add method
now = Calendar.getInstance();
now.add(Calendar.DATE, -10);
System.out.println("date before 10 days : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
}
}
/*
Typical output would be
Current date : 12-25-2007
date after one day : 12-26-2007
date before 10 days : 12-15-2007
*/
Android get date before 7 days (one week)
Date myDate = dateFormat.parse(dateString);
And then either figure out how many milliseconds you need to subtract:
Date newDate = new Date(myDate.getTime() - 604800000L); // 7 * 24 * 60 * 60 * 1000
Or use the API provided by the java.util.Calendar class:
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date newDate = calendar.getTime();
Then, if you need to, convert it back to a String:
and finally
String date = dateFormat.format(newDate);
you can use this kotlin function to get any date before the current date.
/**
* get specific date before current date
* [day] number of day
* [month] number of month
* [year] number of year
* [count] number of day, month, year
*
* return date
*/
fun getBeforeDate(day: Boolean = false, month: Boolean = false, year: Boolean = false, count: Int = 0): String{
val currentCalendar = Calendar.getInstance()
val myFormat = "dd/MM/yyyy" // you can use your own date format
val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
if (day){
currentCalendar.add(Calendar.DAY_OF_YEAR, -count)
}else if(month){
currentCalendar.add(Calendar.MONTH, -count)
}else if(year){
currentCalendar.add(Calendar.YEAR, -count)
}else{
// if user not provide any value then give current date
currentCalendar.add(Calendar.DAY_OF_YEAR, 0)
// or you can throw Exception
//throw Exception("Please provide at least one value")
}
return sdf.format(currentCalendar.time)
}
fun getBeforeDate(day: Boolean = false, month: Boolean = false, year: Boolean = false, count: Int = 0): String{
val currentCalendar = Calendar.getInstance()
val myFormat = "dd/MM/yyyy" // you can use your own date format
val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
if (day){
currentCalendar.add(Calendar.DAY_OF_YEAR, -count)
}else if(month){
currentCalendar.add(Calendar.MONTH, -count)
}else if(year){
currentCalendar.add(Calendar.YEAR, -count)
}else{
// if user not provide any value then give current date
currentCalendar.add(Calendar.DAY_OF_YEAR, 0)
// or you can throw Exception
//throw Exception("Please provide at least one value")
}
return sdf.format(currentCalendar.time)
}