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
Related
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);
}
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);
}
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;
}
}
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()
I had written a function for Adding time as given below
private void Delay15Minute() {
String pkManifest = manifest.pkManifestNo;
manifest_helper = new manifest_helper(this);
cursor = manifest_helper.GetDeliveries(pkManifest);
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
cursor.getString(cursor.getColumnIndex("PKDelivery"));
// String
// RevisedTime=cursor.getString(cursor.getColumnIndex("RevisedEstimatedDeliveryTime"));
String RevisedTime = "12:55";
// get hour and minute from time string
StringTokenizer st1 = new StringTokenizer(RevisedTime, ":");
int j = 0;
int[] val = new int[st1.countTokens()];
// iterate through tokens
while (st1.hasMoreTokens()) {
val[j] = Integer.parseInt(st1.nextToken());
j++;
}
// call time add method with current hour, minute and minutesToAdd,
// return added time as a string
String date = addTime(val[0], val[1], 15);
// Tioast the new time
Toast.makeText(this, "date is =" + date, Toast.LENGTH_SHORT).show();
}
}
public String addTime(int hour, int minute, int minutesToAdd) {
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
calendar.add(Calendar.MINUTE, minutesToAdd);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String date = sdf.format(calendar.getTime());
return date;
}
I am getting the oupt of this as 01:10 as 12 hours fromat...
I need to get it in 13:10 format ie 24 hour format.....Please help me
You used hh in your SimpleDateFormat pattern. Thats the 12 hour format. Use kk instead, that gives you the hours of the day in a 24 hour format. See SimpleDateFormat.
Simply create the instance of Calendar and get 24 hr time by,
Calendar c = Calendar.getInstance();
int Hr24=c.get(Calendar.HOUR_OF_DAY);
int Min=c.get(Calendar.MINUTE);
Use this code
long date = System.currentTimeMillis();
SimpleDateFormat date1 = new SimpleDateFormat("dd-MM-yyyy"); // for current date
SimpleDateFormat time1 = new SimpleDateFormat("kk:mm:ss"); // for 24 hour time
SimpleDateFormat time2 = new SimpleDateFormat("hh:mm:ss"); // for 12 hour time
String dateString = date1.format(date); //This will return current date in 31-12-2018 format
String timeString1 = time1.format(date); //This will return current time in 24 Hour format
String timeString2 = time2.format(date); //This will return current time in 12 Hour format
Log.e("TAG_1", "24 hour Time - " + timeString1);
Log.e("TAG_1", "24 hour Time - " + timeString1);
Log.e("TAG_1", "dd-MM-yyyy Date format - " + dateString);
than open your logcat to check result.