Get yesterday from simpledataformat - android

It's my code for getting today to long.
Can I get yesterday by using this code?
SimpleDateFormat date_0 = new SimpleDateFormat("yyMMdd");
Date date_1 = new Date();
long date_t = Long.valueOf(date_0.format(date_1));
EDIT>
I solve with this
SimpleDateFormat date_0 = new SimpleDateFormat("yyMMdd");
Date date_1 = new Date();
long date_t = Long.valueOf(date_0.format(date_1));
long date_2 = date_1.getTime();
Date yesterday = new Date(date_2 -= 86400000);
long date_y = Long.valueOf(date_0.format(yesterday));

You could take the current date, and subtract 86400000 milliseconds (equivalent to one day).
SimpleDateFormat date_0 = new SimpleDateFormat("yyMMdd");
Date date_1 = new Date();
long date_t = date_1.getTime();
date_t -= 86400000;
Date yesterday = new Date(date_t);
System.out.println("Yesterday's Date: " + date_0.format(yesterday));

I'm not sure but this should work:
SimpleDateFormat date_0 = new SimpleDateFormat("yyMMdd");
Date date_1 = new Date();
date_1.setDate(date_1.getDay()-1);
long date_t = Long.valueOf(date_0.format(date_1));

SimpleDateFormat date_0 = new SimpleDateFormat("yyMMdd");
Calendar calendar = Calendar.getInstance(); // this is default system date
calendar.add(Calendar.DAY_OF_MONTH, -1); // minus date to previous day
long date_t = Long.valueOf(date_0.format(calendar.getTime())); // convert into long
System.out.println(date_0.format(calendar.getTime())); // system print 151110

You can use Joda-Time. The design allows for multiple calendar systems, while still providing a simple API.
private DateTime getPreviousDateAndTime(int previousCount){
DateTimeFormat format = DateTimeFormat.forPattern("yyyy-MM-dd 00:00:00.000000000");
DateTime now = new DateTime();
DateTime expectedDate = now.minusDays(previousCount);
return expectedDate;
}
Add the following dependency to build.gradle:
dependencies {
compile 'net.danlew:android.joda:2.9.0'
}

Simple..
private Calendar calendar;
public void getPreviousDay() {
calendar.add(Calendar.DATE, -1);
}

Related

Android: Check if MySQL timestamp is today or yesterday ELSE output formatted timestamp

so I am getting timestamp from MySQL database which is in following format: 2014-12-09 16:46:26
I want before applying that Date to TextView - to check if date is today or yesterday.
Basically like:
if(timestamp == today){
TextView = "Today";
}
else if(timestamp == yesterday){
TextView = "Yesterday";
}
else{
TextView = FormatTimeStamp(DD/MM/YY hh:mm);
}
I was writing this code:
String dats = timestamp; //2014-12-09 16:46:26
String[] datsdt = dats.split("\\s+");
String[] dateSplit = datsdt[0].split("\\-");
String[] timeSplit = datsdt[1].split("\\:");
int year = Calendar.getInstance().get(Calendar.YEAR);
int month = Calendar.getInstance().get(Calendar.MONTH);
int day = Calendar.getInstance().get(Calendar.DATE);
Then compare split date parts with current year month and day, but that seems way too long and I am sure it's wrong way of doing it.
So how do I do this?
Use SimpleDateFormat to parse the Date and Calendar to compare the dates.:
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd hh:mm:ss");
Date date = sdf.parse("2014-12-09 16:46:26");
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);
Calendar yesterday = Calendar.getInstance();
yesterday.add(Calendar.DAY_OF_MONTH, -1);
yesterday.set(Calendar.HOUR_OF_DAY,0);
yesterday.set(Calendar.MINUTE,0);
yesterday.set(Calendar.SECOND,0);
yesterday.set(Calendar.MILLISECOND,0);
if (c.getTime().equals(new Date())){
//TODAY
} else if (c.equals(yesterday)) {
//yesterday
} else {
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy hh:mm");
TextView = sdf1.format(date);
}

To get Date and time from Timestamp 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;
}
}

How to find difference between two dates which is in string format in android

Calendar zCalendarL = Calendar.getInstance();
SimpleDateFormat zDateFormatL = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String DateTime="2013/02/15 15:05:01";
String zUpdatedDateTimeG =zDateFormatL.format(DateTime);
String zCurrentDateTimeL=zDateFormatL.format(zCalendarL.getTime());
I need to know the date time between zCurrentDateTimeL and zUpdatedDateTimeG
How to do it?
try this:
I hope this will be help to you this is worked for me...
private void getDifference(java.util.Date startTime,
java.util.Date endTime, java.util.Date eartime,
java.util.Date curtime) {
Calendar startDateTime = Calendar.getInstance(TimeZone
.getTimeZone("GMT-5:00"));
startDateTime.setTime(startTime);
Calendar endDateTime = Calendar.getInstance();
endDateTime.setTime(endTime);
long milliseconds1 = startDateTime.getTimeInMillis();
long milliseconds2 = endDateTime.getTimeInMillis();
long diff = Math.abs(milliseconds1 - milliseconds2);
long seconds = diff / (1000);
}
Calendar zCalendarL = Calendar.getInstance();
SimpleDateFormat zDateFormatL = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String DateTime="2013/02/15 15:05:01";
Date d = zDateFormatL.parse(DateTime);
long diff = System.currentTimeMillis() - d.getTime();
this will return the difference in miliseconds

how to get the current date of android phone?

This is how i get the phone's date, but it prompts me with a parseException, what's the problem?
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(new Date());
Date localDate = sdf.parse(date);
new Date(0) is not the current date/time. You should use new Date(). ParseException should go away then. If you wanna know why you got that, simply debug your program and have a look at what new Date(0) gives as a String, you'll know why it fails to be parsed.
Date now = new Date();
Date alsoNow = Calendar.getInstance().getTime();
String nowAsString = new SimpleDateFormat("yyyy-MM-dd").format(now);
That works. And that too:
Date christmas = new SimpleDateFormat("yyyy-MM-dd").parse("2012-12-25");
By the way, make sure you are using java.util.Date and not java.sql.Date
Calendar now = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String nowDate = formatter.format(now.getTime());
String[] separateCurrentDate = nowDate.split("-");
String year = separateCurrentDate[0];
String month = separateCurrentDate[1];
String day = separateCurrentDate[2];
int currentYear = Integer.parseInt(year);
int currentMonth = Integer.parseInt(month);
int currentDay = Integer.parseInt(day);
and then store y,m,d one by one into a Date type onject
Date now = new Date();
Date alsoNow = Calendar.getInstance().getTime();
String nowAsString = new SimpleDateFormat("yyyy-MM-dd").format(now);
currentdate = (TextView)findViewById(R.id.textcntdate);
currentdate.setText(nowAsString);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
And then also here is another link on this
Display the current time and date in an Android application

Android: Calendar not returning values?

I'm trying to run this little code to return a eight-digit integer to be used in a for-loop later on as a search function. Problem is that it doesn't return any values for searchDateToday. Am I missing something?
final Calendar cal = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
DateToday = formatter.format(cal.getTime()); // YYYYMMDD form -
// Example: 20111010
// = October 10,
// 2011
int searchDateToday = Integer.parseInt(DateToday);
You forgot to use the Date object:
final Calendar cal = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
DateToday = formatter.format(new Date(cal.getTime()));
// YYYYMMDD form -// Example: 20111010 // = October 10, // 2011
int searchDateToday = Integer.parseInt(DateToday);
use this for getting today date
String currentDate = DateFormat.getDateInstance().format(new Date());
tv_date.setText(currentDate); // tv_date is TextView

Categories

Resources