To get Date and time from Timestamp Android - android

I want to get time and date separately from timestamp.Please help me in these. My example of timestamp is 1378798459.
Thanks

//Try the following
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(new Date(Long.parseLong(YOUR TIMESTAMP VALUE)));
txtDate.setText(dateString);
//You can put your needed format here:
SimpleDateFormat formatter = new SimpleDateFormat("YOUR REQUIRED FORMAT");

Try this is working with me
public String getDateCurrentTimeZone(long timestamp) {
try{
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
calendar.setTimeInMillis(timestamp * 1000);
calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currenTimeZone = (Date) calendar.getTime();
return sdf.format(currenTimeZone);
}catch (Exception e) {
}
return "";
}

Improving upon the answer given by Pratik Dasa
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Here you can get various formats using the following syntax. You can play around with it by deleting or adding terms given below in the syntax.
Date and Time Pattern Result
----------------------------- ---------------------------------
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u" 2001-W27-3

String time = DateUtils.formatDateTime(this, 1378798459, DateUtils.FORMAT_SHOW_TIME);
String date = DateUtils.formatDateTime(this, 1378798459, DateUtils.FORMAT_SHOW_DATE);

Try this,
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
Date date = cal.getTime();
mHour = date.getHours();
mMinute = date.getMinutes();

Only that:
long timestampString = Long.parseLong("yourString");
String value = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").
format(new java.util.Date(timestampString * 1000));

long dv = Long.valueOf(timestamp_in_string)*1000;// its need to be in milisecond
Date df = new java.util.Date(dv);
String vv = new SimpleDateFormat("MM dd, yyyy hh:mma").format(df);
From here.

you can use this
Long tsLong = System.currentTimeMillis();
String ts = tsLong.toString();
long millisecond = Long.parseLong(ts);
datetimeString = DateFormat.format("MM-dd-yyyy hh:mm:ss a", new Date(millisecond)).toString();
timeString = datetimeString.substring(11);
dateString = datetimeString.substring(0,10);
String t2 = datetimeString.substring(20,21);
The datetimeString contains the Date Time AM/PM data
timeString will give you the substring which contains the time only and the dateString is substring for date
The String t2 will give you whether it is AM or PM in the clock

int day, month, year;
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();
day = date.get(Calendar.DAY_OF_MONTH);
month = date.get(Calendar.MONTH);
year = date.get(Calendar.YEAR);
second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);
String data =(hour+ ':'+ ""+minute+ ':'+"" +second+"" +""+"" +day+"" +"/" +(month+1)+"" +"/"+ +year);
Toast.makeText(getActivity(), "Time stamp:"+data,Toast.LENGTH_LONG).show();

DateFormat dateFormat = DateFormat.getDateTimeInstance();
when.setText(dateFormat.format(new Date(timestamp * 1000)));
The timestamp is multiplied by 1000 for converting the seconds into milliseconds.

All the answers are great and they mainly focus on converting the unix timestamp to milliseconds first, which is correct.
I struggled to apply that because I must use 1000L in the conversion (instead of 1000 only). Here's my working code with time zone conversion
// Set TimeZone
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yy h:mm a", Locale.US);
dateFormat.setTimeZone(getDeviceTimeZone());
// Set time
Date date = new Date(timestamp * 1000L);
return dateFormat.format(date);
For Android API 26 and above, you can just do
return Instant.ofEpochSecond( timestamp )
.atZone(ZoneId.of( timezone ))
.toLocalDateTime()
.toString();

The very best way to get day and date from the timestamp is that:
java.util.Date dayAndDate = new java.util.Date( (long) yourTimeStamp * 1000);
// object coming as like: Tue Feb 09
String day = dayAndDate.toString().split(" ")[0];
String month = dayAndDate.toString().split(" ")[1];
String date = dayAndDate.toString().split(" ")[2];
I hope you will like my approach, if you have liked it, don't forget to give it an upvote, so that others will consider it.

If you want to use time like in a WhatsApp message, You can use this method,
public static String millisToDateChat(long time) {
long currentTime = System.currentTimeMillis();
long defe = currentTime - time;
long time_in;
if(time!=0){
time_in = time;
}else{
time_in = currentTime;
defe = 0;
}
int s = (int)defe/1000;
int m = (int)defe/(1000*60);
int h = (int)defe/(1000*60*60);
int d = (int)defe/(1000*60*60*24);
int w = (int)defe/(1000*60*60*24*7);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time_in);
Date date = calendar.getTime();
#SuppressLint("SimpleDateFormat") String formattedDate=(new SimpleDateFormat("HH:mm")).format(date);
#SuppressLint("SimpleDateFormat") String formattedYear=(new SimpleDateFormat("MMM d, ''yy")).format(date);
#SuppressLint("SimpleDateFormat") String formattedm=(new SimpleDateFormat("MMM d")).format(date);
if(d>365) {
return formattedYear;
}else if(s>172000){
return formattedm;
}else if(s>86400) {
return "Yest.";
}else{
return formattedDate;
}
}

Related

Timestamp to Date/Time

I am trying to make a football Livescore app. And I need to show the match time to users as their local match time.
if I was generated a Timestamp from a given timezone, lets say it is
autodatetime(1517009400,6.5); //original timezone included
//I can make it done in javascript by https://www.autodatetime.com/
But I was trying to get it from Android with this code
public String getconvertedtime(long timestamp) {
try{
Toast.makeText(getApplicationContext(),Integer.toString(TimeZone.getDefault().getDSTSavings()),Toast.LENGTH_LONG).show();
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
//getTimezonedifference() return 0 for me
timestamp= timestamp-getTimezonedifference();
calendar.setTimeInMillis(timestamp * 1000);
calendar.add(Calendar.MILLISECOND, (tz.getOffset(calendar.getTimeInMillis())-tz.getDSTSavings()));
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
Date currentTimeZone = calendar.getTime();
return dateFormat.format(currentTimeZone);
}catch (Exception e) {
return "";
}
}
public int getTimezonedifference() {
TimeZone tz = TimeZone.getDefault();
Calendar cal = GregorianCalendar.getInstance(tz);
double offsetInMillis = tz.getOffset(cal.getTimeInMillis());
//String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
//offset = "GMT"+(offsetInMillis >= 0 ? "+" : "-") + offset;
offsetInMillis= Math.abs((offsetInMillis)-(6.5*3600000));
int vall=(int)offsetInMillis;
return vall;
}
Unfortunately It was returning wrong time, I can't figure it out why it was showing faster hours .
The result is 01/27/2018 12:30:00 PM
It must be 01/26/2018 11:30:00 PM for my Local TimeZone(6.5)
And I found something about different DST problems from googling and get 0 from "TimeZone.getDefault().getDSTSavings()" on Toast.
Please guide me to the solution, I am new to android programming. Thank you for reading.
Given epoch of 1517009400, which is 01/26/2018 23:30:00 GMT, to show this time in user's local time:
// convert to epoch milli seconds
long ts = 1517009400000l;
Date date = new Date(ts);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String dateStr = dateFormat.format(date);
android.util.Log.i("TEST", "dateStr: " + dateStr);
dateStr will be formatted according to timezone of user's phone. For example, my phone is set to Asia/Kuala_Lumpur timezone, which is GMT+8, so it shows 01/27/2018 07:30:00.
To format date string into particular timezone (eg: New York), you can try this:
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String dateStr = dateFormat.format(date);
This outputs 01/26/2018 18:30:00.

How to fetch recent seven days from specific date

If the date is 2017-03-30 that i want to fetch the date from 2017-03-23 to 2017-03-30
I try to use this code let my String change to Date format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dateParse = sdf.parse("2017-03-30");
then i'm stuck , cause i take the reference is get the current time like this
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -7);
//may be my dateParse should put here , but i don't know how to do
Date monday = c.getTime();//it get the current time
String preMonday = sdf.format(monday);
Is any one can teach me how to fetch these seven days ? Thanks in advance.
You can use the code below
SimpleDateFormatdateFormat = new SimpleDateFormat("dd MMM yyyy");
Calendar c = Calendar.getInstance();
String date = dateFormat.format(c.getTime());
c.add(Calendar.DATE, 7);
String date1 = dateFormat.format(c.getTime());
Parse the date:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = sdf.parse("2017-03-30");
First Solution 1) And then either figure out how many milliseconds you need to subtract:
Date newDate = new Date(myDate.getTime() - 604800000L); // 7 * 24 * 60 * 60 * 1000
Second Solution 2) 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:
String date = dateFormat.format(newDate);
This answer is from here
EDIT:
If you need output as 2017-03-29 2017-03-28 2017-03-27 ...... 2017-03-23 then try below code
for(int i = 1; i <= 7; i++){
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -i);
Date newDate = calendar.getTime();
String date = dateFormat.format(newDate);
//here in date you can get all date from and output as 2017-03-29 2017-03-28 2017-03-27 ...... 2017-03-23
}
Hope you need this

How convert timestamp to date on android?

I want convert timestamp to date and set time in this day to 12.00.
How can I do this?
If I use this:
Date date = new Date(event.getActionDate()*1000);
I can't set hour or minutes to this date, becouse methods for this operations are deprecated.
Explanation:
I have timestamp -
1461924872 // Fri, 29 Apr 2016 10:14:32 GMT
I want change hour in this timestamp (10:14 to 00.00).
long timeInMillis = 1461877200000l;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeInMillis);
System.out.println("Date1:"+calendar.getTime().toString());
calendar.set(Calendar.HOUR_OF_DAY, 0); //For 12 AM use 0 and for 12 PM use 12.
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date date = calendar.getTime();
System.out.println("Date2:"+date.toString());
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();//get your local time zone.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
sdf.setTimeZone(tz);//set time zone.
String localTime = sdf.format(new Date(time) * 1000));
Date date = new Date();
date = sdf.parse(localTime);
private String getDate(String timeStampStr){
try{
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date netDate = (new Date(Long.parseLong(timeStampStr)));
return sdf.format(netDate);
}
catch(Exception ex){
return dateInStr;
}
}
let me know if it is working?

How to convert Java.Util.Date to System.DateTime

In Xamarin.Android, you work with both .NET and Java.
I get a return value of Java.Util.Date, I then need to input that same value as a parameter that only takes System.DateTime
This is how I currently do it
public static DateTime ConvertJavaDateToDateTime(Date date)
{
var a = date.ToGMTString();
var b = date.ToLocaleString();
var c = date.ToString();
DateTime datetime = DateTime.ParseExact(date.ToGMTString(), "dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture);
return datetime;
}
However on the first 9 days of any month, I only get 1 digit for the day, and the
DateTime.ParseExact function is looking for dd (i.e. 2 digits for the day).
a is a string with value "1 Sep 2014 14:32:25 GMT"
b is a string with value "1 Sep 2014 16:32:25"
c is a string with value "Mon Sep 01 16:32:25 EET 2014"
I wish I could find a simple, quick, reliable and consistent solution for this problem :D
java.util.Date has a getTime() method, which returns the date as a millisecond value. The value is the number of milliseconds since Jan. 1, 1970, midnight GMT.
With that knowledge, you can construct a System.DateTime, that matches this value like so:
public DateTime FromUnixTime(long unixTimeMillis)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddMilliseconds(unixTimeMillis);
}
(method taken from this answer)
Do this:
public DateTime ConvertDateToDateTime(Date date)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
String dateFormated = dateFormat.format(date);
return new DateTime(dateFormated);
}
I'll update my answer, since you've changed the question.
you can use a long to hold the milliseconds and than convert the milliseconds to ticks(x10000) and create a new DateTime
Date date = new Date();
Long milliseconds = date.getTime();
Long ticks = milliseconds * 10000
DateTime datetime = DateTime(ticks);
I had this problem when authenticating with Facebook to receive the Expire time for the token. The solution was to do this:
var convertedTime = new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc).AddMilliseconds(MyJavaUtil.Date.Time);
I used this:
DateTimeOffset.FromUnixTimeMilliseconds(date.Time - (date.TimezoneOffset * 60 * 1000)).DateTime;
To incorporate the timezone offset into my date.
In my case, only this code works correctly:
public static DateTime NativeDateToDateTime(Java.Util.Date date)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
string dateFormated = dateFormat.Format(date);
return DateTimeOffset.Parse(dateFormated, null, DateTimeStyles.None).DateTime;
}
It is not tested but try with Calendar methods
public static String ConvertJavaDateToDateTime(Date date)
{
Calendar c = new GregorianCalendar();
c.setTime(date);
System.out.println(c.getTime());
return c.getTime();
}
Prints:
Tue Aug 06 00:00:00 EDT 2013
You can try with this also
public DateTime dateAndTimeToDateTime(java.sql.Date date, java.sql.Time time) {
String myDate = date + " " + time;
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss 'GMT'");
java.util.Date utilDate = new java.util.Date();
try {
utilDate = sdf.parse(myDate);
} catch (ParseException pe){
pe.printStackTrace();
}
DateTime dateTime = new DateTime(utilDate);
return dateTime;
}

get current date and time

I'm kind of stuck on date and time.
I want my program to create the date like this "20121217". The first 4 letters are the year, the second 2 letters are the month and the last 2 are the day. year+month+day
The time is "112233" hour+minute+second
Thanks for your help!
That's a formatting issue. Java uses java.util.Date and java.text.DateFormat and java.text.SimpleDateFormat for those things.
DateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd hhmmss");
dateFormatter.setLenient(false);
Date today = new Date();
String s = dateFormatter.format(today);
You can do something like this:
Calendar c = Calendar.getInstance();
String date = c.get(Calendar.YEAR) + c.get(Calendar.MONTH) + c.get(Calendar.DATE);
String time = c.get(Calendar.HOUR) + c.get(Calendar.MINUTE) + c.get(Calendar.SECOND);
Change any specific format of time or date as you need.
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
currentDateandTime = sdf.format(new Date());
For date:
DateFormat df = new SimpleDateFormat("yyyyMMdd");
String strDate = df.format(new Date());
For time:
DateFormat df = new SimpleDateFormat("hhmmss");
String strTime = df.format(new Date());
This works,
String currentDateTime;
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
currentDateTime = sdf1.format(new Date());
What you're looking for is the SimpleDateFormat in Java... Take a look at this page.
Try this for your need:
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd hhmmss");
Date parsed = format.parse(new Date());
System.out.println(parsed.toString());
You can use following method to get current time
/**************************************************************
* getCurrentTime() it will return system time
*
* #return
****************************************************************/
public static String getCurrentTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HHmmss");
Calendar cal = Calendar.getInstance();
return dateFormat.format(cal.getTime());
}// end of getCurrentTime()

Categories

Resources