Получить текущее время java android

Display the current time and date in an Android application

Okay, not that hard as there are several methods to do this. I assume you want to put the current date & time into a TextView .

String currentDateTimeString = java.text.DateFormat.getDateTimeInstance().format(new Date()); // textView is the TextView view that should display it textView.setText(currentDateTimeString); 

There is more to read in the documentation that can easily be found here . There you’ll find more information on how to change the format used for conversion.

Please — be more explicit! What’s the error? Did you import the wrong DateFormat class? It’s java.text.DateFormat and NOT android.text.format.DateFormat ! And it’s java.util.Date and NOT java.sql.Date ! Just a little hint on asking questions: try to be precise, e.g.: declare what you mean by «display» in your question. And when you type in my lines — both Date and DateFormat must, of course, be imported — if there’s a choice of 2 for each, the least you could try is any combination: it’s just 4!

Have a look at developer.android.com/reference/java/text/SimpleDateFormat.html — there you can see how to define exactly what you want to be in your output string. E.g. for time use «HH:mm:ss» ! Completely: currentTimeString = new SimpleDateFormat(«HH:mm:ss»).format(new Date());

How efficient is this? Let’s say you need to get time from a constantly firing method. Is there anything more efficient than creating a new Date object each time?

public class XYZ extends Activity < /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); //setContentView(R.layout.main); Calendar c = Calendar.getInstance(); System.out.println("Current time =>"+c.getTime()); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate = df.format(c.getTime()); // formattedDate have current date/time Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show(); // Now we display formattedDate value in TextView TextView txtView = new TextView(this); txtView.setText("Current Date and Time : "+formattedDate); txtView.setGravity(Gravity.CENTER); txtView.setTextSize(20); setContentView(txtView); > > 

enter image description here

public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.main); Thread myThread = null; Runnable runnable = new CountDownRunner(); myThread= new Thread(runnable); myThread.start(); >public void doWork() < runOnUiThread(new Runnable() < public void run() < try< TextView txtCurrentTime= (TextView)findViewById(R.id.lbltime); Date dt = new Date(); int hours = dt.getHours(); int minutes = dt.getMinutes(); int seconds = dt.getSeconds(); String curTime = hours + ":" + minutes + ":" + seconds; txtCurrentTime.setText(curTime); >catch (Exception e) <> > >); > class CountDownRunner implements Runnable < // @Override public void run() < while(!Thread.currentThread().isInterrupted())< try < doWork(); Thread.sleep(1000); >catch (InterruptedException e) < Thread.currentThread().interrupt(); >catch(Exception e) < >> > > 

I know this is old question, but if somebody will find it in google like me, he should know that the methods Date.getX are deprecated.

Читайте также:  Csv python empty row

The obvious choices for displaying the time are the AnalogClock View and the DigitalClock View.

For example, the following layout:

screenshot

I feel like a stupid shit after reading this obvious answer! I implemented my own runnable, putting it to sleep for a given amount of time and so on when the obvious answer was a XML-one-liner! Many thanks (more than a year after your post) 🙂

AnalogClock is deprecated in API level 23. and AnalogClock and DigitalClock only show current time, but not current date.

In case you want a single line of code:

String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); 

The result is «2016-09-25 16:50:34»

Calendar c = Calendar.getInstance(); String sDate = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH) + " at " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE); 

I wonder why c.get(Calendar.MONTH) returns 5 when it is supposedly 6? My device has correct time settings.

Calendar c = Calendar.getInstance(); int month = c.get(Calendar.MONTH) + 1; String sDate = month + «-» + c.get(Calendar.DAY_OF_MONTH) + «-» + c.get(Calendar.YEAR) + «-» + c.get(Calendar.HOUR_OF_DAY) + «:» + c.get(Calendar.MINUTE); that works fine

If you want to get the date and time in a specific pattern you can use

Date d = new Date(); CharSequence s = DateFormat.format("yyyy-MM-dd hh:mm:ss", d.getTime()); 
android.text.format.DateFormat.getDateFormat(Context context) android.text.format.DateFormat.getTimeFormat(Context context) 

to get valid time and date formats in sense of current user settings (12/24 time format, for example).

import android.text.format.DateFormat; private void some() < final Calendar t = Calendar.getInstance(); textView.setText(DateFormat.getTimeFormat(this/*Context*/).format(t.getTime())); >

Here is the code which worked for me. Please try this. It is a simple method which takes time and date from a system call.

public static String getDatetime() < Calendar c = Calendar .getInstance(); System.out.println("Current time =>"+c.getTime()); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mms"); String formattedDate = df.format(c.getTime()); return formattedDate; > 
Calendar c = Calendar.getInstance(); int seconds = c.get(Calendar.SECOND); int minutes = c.get(Calendar.MINUTE); int hour = c.get(Calendar.HOUR); String time = hour + ":" + minutes + ":" + seconds; int day = c.get(Calendar.DAY_OF_MONTH); int month = c.get(Calendar.MONTH); int year = c.get(Calendar.YEAR); String date = day + "/" + month + "/" + year; // Assuming that you need date and time in a separate // textview named txt_date and txt_time. txt_date.setText(date); txt_time.setText(time); 
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); 

Use formattedDate as your String filled with the date.
In my case: mDateButton.setText(formattedDate);

Actually, you’re best off with the TextClock widget. It handles all of the complexity for you and will respect the user’s 12/24hr preferences. http://developer.android.com/reference/android/widget/TextClock.html

To display the current date function:

Calendar c = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy"); String date = df.format(c.getTime()); Date.setText(date); 

import java.text.SimpleDateFormat; import java.util.Calendar;

TextView Date; Date = (TextView) findViewById(R.id.Date); 
Calendar c = Calendar.getInstance(); int month=c.get(Calendar.MONTH)+1; String sDate = c.get(Calendar.YEAR) + "-" + month+ "-" + c.get(Calendar.DAY_OF_MONTH) + "T" + c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND); 

This will give date time format like 2010-05-24T18:13:00

This would give the current date and time:

public String getCurrDate()

Simply copy this code and hope this works fine for you.

Calendar c = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a"); String strDate = sdf.format(c.getTime()); 
String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); Toast.makeText(getApplicationContext(), currentDateandTime, Toast.LENGTH_SHORT).show(); 
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); System.out.println("time => " + dateFormat.format(cal.getTime())); String time_str = dateFormat.format(cal.getTime()); String[] s = time_str.split(" "); for (int i = 0; i < s.length; i++) < System.out.println("date =>" + s[i]); > int year_sys = Integer.parseInt(s[0].split("/")[0]); int month_sys = Integer.parseInt(s[0].split("/")[1]); int day_sys = Integer.parseInt(s[0].split("/")[2]); int hour_sys = Integer.parseInt(s[1].split(":")[0]); int min_sys = Integer.parseInt(s[1].split(":")[1]); System.out.println("year_sys => " + year_sys); System.out.println("month_sys => " + month_sys); System.out.println("day_sys => " + day_sys); System.out.println("hour_sys => " + hour_sys); System.out.println("min_sys => " + min_sys); 

Источник

Android Get Current timestamp?

FYI, the troublesome old date-time classes such as java.util.Date , java.util.Calendar , and Timestamp are now legacy, supplanted by the java.time classes. Most of the java.time functionality is back-ported to Java 6 & Java 7 in the ThreeTen-Backport project. Further adapted for earlier Android in the ThreeTenABP project. See How to use ThreeTenABP….

14 Answers 14

Long tsLong = System.currentTimeMillis()/1000; String ts = tsLong.toString(); 

System.currentTimeMillis() is the standard «wall» clock (time and date) expressing milliseconds since the epoch. The wall clock can be set by the user or the phone network (see setCurrentTimeMillis(long)), so the time may jump backwards or forwards unpredictably. This clock should only be used when correspondence with real-world dates and times is important, such as in a calendar or alarm clock application. Interval or elapsed time measurements should use a different clock. If you are using System.currentTimeMillis() , consider listening to the ACTION_TIME_TICK , ACTION_TIME_CHANGED and ACTION_TIMEZONE_CHANGED Intent broadcasts to find out when the time changes.

From developer.android.com/reference/java/lang/… I found that System.nanoTime() is an alternative to System.currentTimeMillis() and it has no unpredictable fluctuations, and is designed for measuring duration differences.

@ana01 «the zero value is typically whenever the device last booted» — so it can be used only when you compare duration differences on the same device. Not useful for database storage for example.

Just a note to @ana01 ‘s comment that System.nanoTime() isn’t suitable for to display wall clock time. For that purpose, use System.currentTimeMillis() instead.

1320917972 is Unix timestamp using number of seconds since 00:00:00 UTC on January 1, 1970. You can use TimeUnit class for unit conversion — from System.currentTimeMillis() to seconds.

String timeStamp = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())); 
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss"); String format = s.format(new Date()); 

Not a timestamp, and moreover, not efficiant at all (creation of SimpleDateFormat, creation of date, conversion). Avoid it.

Use below method to get current time stamp. It works fine for me.

/** * * @return yyyy-MM-dd HH:mm:ss formate date as string */ public static String getCurrentTimeStamp() < try < SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String currentDateTime = dateFormat.format(new Date()); // Find todays date return currentDateTime; >catch (Exception e) < e.printStackTrace(); return null; >> 

@Hits, It’s Simple Date Format, not a timestamp. You are just using variable name as currentTimeStap.

long millis = new Date().getTime(); 

if you want it in particular format then you need Formatter like below

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String millisInString = dateFormat.format(new Date()); 

You can get Current timestamp in Android by trying below code

time.setText(String.valueOf(System.currentTimeMillis())); 

and timeStamp to time format

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); String dateString = formatter.format(new Date(Long.parseLong(time.getText().toString()))); time.setText(dateString); 

enter image description here

Here is the comparison list of the most widely known methods

Here’s a human-readable time stamp that may be used in a file name, just in case someone needs the same thing that I needed:

package com.example.xyz; import android.text.format.Time; /** * Clock utility. */ public class Clock < /** * Get current time in human-readable form. * @return current time as a string. */ public static String getNow() < Time now = new Time(); now.setToNow(); String sTime = now.format("%Y_%m_%d %T"); return sTime; >/** * Get current time in human-readable form without spaces and special characters. * The returned value may be used to compose a file name. * @return current time as a string. */ public static String getTimeStamp() < Time now = new Time(); now.setToNow(); String sTime = now.format("%Y_%m_%d_%H_%M_%S"); return sTime; >> 

Hey, Could u also tell the best way to sort a list of timestamps? I was thinking of sorting them myself but thought there may be a better way.

For future reference for anybody reading this be aware that «android.text.format.Time» is now deprecated

val nowInEpoch = Instant.now().epochSecond 

Make sure your minimum SDK version is 26.

java.time

I should like to contribute the modern answer.

 String ts = String.valueOf(Instant.now().getEpochSecond()); System.out.println(ts); 

Output when running just now:

While division by 1000 won’t come as a surprise to many, doing your own time conversions can get hard to read pretty fast, so it’s a bad habit to get into when you can avoid it.

The Instant class that I am using is part of java.time, the modern Java date and time API. It’s built-in on new Android versions, API level 26 and up. If you are programming for older Android, you may get the backport, see below. If you don’t want to do that, understandably, I’d still use a built-in conversion:

 String ts = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())); System.out.println(ts); 

This is the same as the answer by sealskej. Output is the same as before.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
  • Oracle tutorial: Date Time explaining how to use java.time .
  • Java Specification Request (JSR) 310, where java.time was first described.
  • ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
  • ThreeTenABP, Android edition of ThreeTen Backport
  • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Источник

Оцените статью