I need to show the device time in the chat messenger but it shows only the zone time.If I change the device time both time will be not same.
I want to display the current device time in Timestamp I used joda.Please check my code.
DateTime createdAt = message.getCreatedAt();
DateTimeZone dateTimeZone= DateTimeZone.getDefault();
DateTimeFormatter fmtTimeBubble = DateTimeFormat.forPattern(LBUtil.TIME_AM_PM_FORMAT).withZone(dateTimeZone);
viewHolder.dateTime.setText(fmtTimeBubble.print(createdAt));
Use below method for getting time according to any timezone, you have to pass 3 parameters as :
System Current time in millis.
Device timezone
And, format of time like (MMM dd, hh:mm a)
public static String getFormatedTime(long dateTime,String timeZone, String format){
String time = null;
try{
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(dateTime);
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
time = sdf.format(cal.getTime());
}
catch(Exception e){
//logger.log(Level.SEVERE,"\n ERROR**********, Exception during get formated time: "+e+"\n");
}
return time;
}
For Calling this method, you have to get device timezone programmatically :
Calendar calendar = Calendar.getInstance();
TimeZone zone = calendar.getTimeZone();
String timeZone = zone.getID();
Now Call this method :
String msgAtTime = getFormattedTime(System.currentTimeInMillis(), timezone, "MMM dd, hh:mm a");
Now, set return String in textview.
msgTextVies.setText(msgAtTime);
Related
I am trying to send a date and time to my SQL oracle database through my REST service. However, the field in the SQL database is getting null.
Here is my code to get the date and time:
public void getCurrentDateandTime() throws ParseException {
Calendar c = Calendar.getInstance();
c.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
currentDateandTime = dateFormat.format(c.getTime());
CDAT = dateFormat.parse(currentDateandTime);
}
In my REST service, this field is specified as a date datatype, however my the temporal I am using is TIMESTAMP as I want to get the date and time.
When I use postman sending through test data like this:
"createdTimestamp": "2018-02-12T09:27:39"
It is being received and shown in my SQL database.
Why is the date I am sending from Android receiving null?
Try this buddy:
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c.getTime());
And then send this formattedDate string. Make it string type and then parse your string as datetime object. Hope this works. Happy Coding :)
Most REST APIs stick with iso8601 format as a standard.
The java code would be like:
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
Then in Oracle to get back is:
to_timestamp('2018-02-14T00:00:00.000Z', 'YYYY-MM-DD"T"HH24:MI:SS.ff3"Z"')
I have a date like this Tue Jun 21 14:47:37 GMT+05:30 2016 , which I create myself. I create it using calendar. Where user selects a date and I save it as milliseconds from calendar.
When I send it , send it, I again create a calendar instance put the saved milliseconds into it and get the date like this :
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(SSPreferences.getDate());
Now while getting date from calendar i do this :
calendar.getTime()//This is what I send to server.
I send it to server, but when server sends me the date, it is always 5.5 hours before my time.
I know my time is GMT+5:50. So what server is doing on its side ?
How do I send the date , such that I get back the same date which I sent to the server.
Any help is appreciated.
Thanks
check this
static final String DATEFORMAT = "yyyy-MM-dd HH:mm:ss"
public static Date GetUTCdatetimeAsDate()
{
//note: doesn't check for null
return StringDateToDate(GetUTCdatetimeAsString());
}
public static String GetUTCdatetimeAsString()
{
final SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
return utcTime;
}
public static Date StringDateToDate(String StrDate)
{
Date dateToReturn = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);
try
{
dateToReturn = (Date)dateFormat.parse(StrDate);
}
catch (ParseException e)
{
e.printStackTrace();
}
return dateToReturn;
}
Finally I solved the issue by adding/subtracting the rawOffSet from the local time zone.
TimeZone timeZone = TimeZone.getDefault();
int offset = timeZone.getOffset(SSPreferences.getDate());
WriteLog.Print("offset is "+offset);
long newtime = SSPreferences.getDate() + offset;
calendar.setTimeInMillis(newtime);
I'm developing an app in which I'm saving the time when the post was posted.
I'm getting that time by using this code:
DateFormat currentTime = new SimpleDateFormat("h:mm a");
final String time = currentTime.format(Calendar.getInstance().getTime());
Now, what I want is I want to get user's timezone and convert the time saved in database using his/her timezone to his/her local time.
I tried doing this using code:
public String convertTime(Date d) {
//You are getting server date as argument, parse your server response and then pass date to this method
SimpleDateFormat sdfAmerica = new SimpleDateFormat("h:mm a");
String actualTime = sdfAmerica.format(d);
//Changed timezone
TimeZone tzInAmerica = TimeZone.getDefault();
sdfAmerica.setTimeZone(tzInAmerica);
convertedTime = sdfAmerica.format(d);
Toast.makeText(getBaseContext(), "actual : " + actualTime + " converted " + convertedTime, Toast.LENGTH_LONG).show();
return convertedTime;
}
but this is not changing the time.
This is how I'm trying to convert time saved in database using above method (postedAtTime is the time which is getting retrieved from database):
String timeStr = postedAtTime;
SimpleDateFormat df = new SimpleDateFormat("h:mm a");
Date date = null;
try {
date = df.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
}
convertTime(date);
Please let me know what's wrong in my code or if this is wrong way?
The time string you're storing is not sufficient to be able to change timezones after the fact (h:mm a is only hours, minutes and am/pm marker). In order to do something like this you need to either store the timezone the original timestamp was in or better yet store the time in a deterministic manner like always UTC.
Example code:
final Date now = new Date();
final String format = "yyyy-MM-dd HH:mm:ss";
final SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
// Convert to UTC for persistence
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
// Persist string to DB - UTC timezone
final String persisted = sdf.format(now);
System.out.println(String.format(Locale.US, "Date is: %s", persisted));
// Parse string from DB - UTC timezone
final Date parsed = sdf.parse(persisted);
// Now convert to whatever timezone for display purposes
final SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm a Z", Locale.US);
displayFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
final String display = displayFormat.format(parsed);
System.out.println(String.format(Locale.US, "Date is: %s", display));
Output
Date is: 2016-06-24 17:49:43
Date is: 13:49 PM -0400
I have retrieved a Date from a SQLiteDatabase and have formatted it to how I want via the following;
String steepingDate = (c.getString(3));
SimpleDateFormat formatter = new SimpleDateFormat("dd/MMM/yyyy");
Date steepingdate = formatter.parse(steepingDate);
I now want to give the user the option to increase whatever date is in steepingdate by a certain amount of days that the user can input
I know you can use;
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 10);
For example to add 10 days onto todays date
But how do you do it so that it uses steepingdate instead of todays date
Thanks
UPDATE;
The calendar is working as I want, but I now want to save the new data to the database, the full code is as following;
String steepingDate = (c.getString(3));
SimpleDateFormat formatter = new SimpleDateFormat("dd/MMM/yyyy");
Date steepingdate = formatter.parse(steepingDate);
Integer amountDays = Integer.parseInt(TSExtend.getText().toString());
Calendar ca = Calendar.getInstance();
ca.setTime(steepingdate);
ca.add(Calendar.DAY_OF_YEAR, amountDays);
DateFormat dateFormat = new SimpleDateFormat("dd/MMM/yyyy");
String newDate = dateFormat.format(ca);
I'm getting the error;
Bad class: class
java.util.GregorianCalendar
Any ideas?
To add 10 days to steepingdate, you can use:
Calendar calendar = Calendar.getInstance();
calendar.setTime(steepingdate);
calendar.add(Calendar.DAY_OF_YEAR, 10);
it the number is provided, through the user interface, you can use the View.OnClickListener and when onClick is fired, read the value from an EditText, and use this value instead of 10
Set the time of the calendar to your date, then add the days
Calendar cal = Calendar.getInstance();
cal.setTime(steepingdate);
cal.add(Calendar.DATE, 10);
UPDATE:
You can't directly format a Calendar, first get the Date from the Calendar, then format it.
String newDate = dateFormat.format(ca.getTime());
I am fetching Newsfeeds from the Facebook API using FQL which returns a "created_time" field as a UNIX Timestamp. I am converting that into, what I believe is a ISO-8601 timestamp using this piece of code:
String getInitialCreatedTime = JOFeeds.getString("created_time");
long finalTimeStamp = Long.valueOf(getInitialCreatedTime);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
String finalCreatedTime = dateFormatter.format(new Date(finalTimeStamp * 1000L));
Now, from the String, finalCreatedTime I want to extract just the time in 12 Hour (AM/PM) format.
To that effect, I am using this code:
final String old_format = "yyyy-MM-dd'T'HH:mm:ssZ";
final String new_format = "EEE MMM d hh:mm aa yyyy";
String oldDateSring = finalCreatedTime;
SimpleDateFormat sdf = new SimpleDateFormat(old_format);
Date d = sdf.parse(oldDateSring);
sdf.applyPattern(new_format);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
And:
// GET THE TIME
SimpleDateFormat sdfTimeFormatter = new SimpleDateFormat("hh:mm aa");
String getTime = sdfTimeFormatter.format(cal.getTime());
feeds.setTime(getTime);
Log.e("TIME", getTime);
The result of the first code block is: 2012-12-14T04:30:03+0530
And the result from the // GET THE TIME block is 04:30AM when it should be 04:30PM.
I would appreciate any pointers on this. Perhaps, I am implementing it wrong?
EDIT: I might add, that timestamps that fall between 12.00 PM and 1.00 PM are handled properly and show PM as they should.
You have :
String getInitialCreatedTime = JOFeeds.getString("created_time");
long finalTimeStamp = Long.valueOf(getInitialCreatedTime);
// Note 8601 is written with 'HH'
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
So far, so good. But then you need to create a date from this.
Date date = new Date(finalTimeStamp * 1000L)
Then, you need to format what you need (and never EVER parse a date you just formatted. That makes no sense at all).
String finalCreatedTime = dateFormatter.format(date); // Not sure if you need this one
And
SimpleDateFormat sdfTimeFormatter = new SimpleDateFormat("hh:mm aa");
String getTime = sdfTimeFormatter.format(date);
feeds.setTime(getTime);