How can I get the current time and date in an Android app?
You could use:
import java.util.Calendar;
import java.util.Date;
Date currentTime = Calendar.getInstance().getTime();
There are plenty of constants in Calendar for everything you need.
Check the Calendar class documentation.
You can (but no longer should - see below!) use android.text.format.Time:
Time now = new Time();
now.setToNow();
From the reference linked above:
The Time class is a faster replacement
for the java.util.Calendar and
java.util.GregorianCalendar classes.
An instance of the Time class
represents a moment in time, specified
with second precision.
NOTE 1:
It's been several years since I wrote this answer,
and it is about an old, Android-specific and now deprecated class.
Google now says that
"[t]his class has a number of issues and it is recommended that GregorianCalendar is used instead".
NOTE 2: Even though the Time class has a toMillis(ignoreDaylightSavings) method, this is merely a convenience to pass to methods that expect time in milliseconds. The time value is only precise to one second; the milliseconds portion is always 000. If in a loop you do
Time time = new Time(); time.setToNow();
Log.d("TIME TEST", Long.toString(time.toMillis(false)));
... do something that takes more than one millisecond, but less than one second ...
The resulting sequence will repeat the same value, such as 1410543204000, until the next second has started, at which time 1410543205000 will begin to repeat.
If you want to get the date and time in a specific pattern you can use the following:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
String currentDateandTime = sdf.format(new Date());
Or,
Date:
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
Time:
String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
For those who might rather prefer a customized format, you can use:
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
Whereas you can have DateFormat patterns such as:
"yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
"hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
"EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
"yyMMddHHmmssZ"-------------------- 010704120856-0700
"K:mm a, z" ----------------------- 0:08 PM, PDT
"h:mm a" -------------------------- 12:08 PM
"EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01
Actually, it's safer to set the current timezone set on the device with Time.getCurrentTimezone(), or else you will get the current time in UTC.
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
Then, you can get all the date fields you want, like, for example:
textViewDay.setText(today.monthDay + ""); // Day of the month (1-31)
textViewMonth.setText(today.month + ""); // Month (0-11)
textViewYear.setText(today.year + ""); // Year
textViewTime.setText(today.format("%k:%M:%S")); // Current time
See android.text.format.Time class for all the details.
UPDATE
As many people are pointing out, Google says this class has a number of issues and is not supposed to be used anymore:
This class has a number of issues and it is recommended that
GregorianCalendar is used instead.
Known issues:
For historical reasons when performing time calculations all
arithmetic currently takes place using 32-bit integers. This limits
the reliable time range representable from 1902 until 2037.See the
wikipedia article on the Year 2038 problem for details. Do not rely on
this behavior; it may change in the future. Calling
switchTimezone(String) on a date that cannot exist, such as a wall
time that was skipped due to a DST transition, will result in a date
in 1969 (i.e. -1, or 1 second before 1st Jan 1970 UTC). Much of the
formatting / parsing assumes ASCII text and is therefore not suitable
for use with non-ASCII scripts.
tl;dr
Instant.now() // Current moment in UTC.
…or…
ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ) // In a particular time zone
Details
The other answers, while correct, are outdated. The old date-time classes have proven to be poorly designed, confusing, and troublesome.
java.time
Those old classes have been supplanted by the java.time framework.
Java 8 and later: The java.time framework is built-in.
Java 7 & 6: Use the backport of java.time.
Android: Use this wrapped version of that backport.
These new classes are inspired by the highly successful Joda-Time project, defined by JSR 310, and extended by the ThreeTen-Extra project.
See the Oracle Tutorial.
Instant
An Instant is a moment on the timeline in UTC with resolution up to nanoseconds.
Instant instant = Instant.now(); // Current moment in UTC.
Time Zone
Apply a time zone (ZoneId) to get a ZonedDateTime. If you omit the time zone your JVM’s current default time zone is implicitly applied. Better to specify explicitly the desired/expected time zone.
Use proper time zone names in the format of continent/region such as America/Montreal, Europe/Brussels, or Asia/Kolkata. Never use the 3-4 letter abbreviations such as EST or IST as they are neither standardized nor unique.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Generating Strings
You can easily generate a String as a textual representation of the date-time value. You can go with a standard format, your own custom format, or an automatically localized format.
ISO 8601
You can call the toString methods to get text formatted using the common and sensible ISO 8601 standard.
String output = instant.toString();
2016-03-23T03:09:01.613Z
Note that for ZonedDateTime, the toString method extends the ISO 8601 standard by appending the name of the time zone in square brackets. Extremely useful and important information, but not standard.
2016-03-22T20:09:01.613-08:00[America/Los_Angeles]
Custom format
Or specify your own particular formatting pattern with the DateTimeFormatter class.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy hh:mm a" );
Specify a Locale for a human language (English, French, etc.) to use in translating the name of day/month and also in defining cultural norms such as the order of year and month and date. Note that Locale has nothing to do with time zone.
formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
String output = zdt.format( formatter );
Localizing
Better yet, let java.time do the work of localizing automatically.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) ); // Or Locale.CANADA_FRENCH and so on.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where can the java.time classes be obtained?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
For the current date and time, use:
String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
Which outputs:
Feb 27, 2012 5:41:23 PM
Try with the following way. All formats are given below to get the date and time formats.
Calendar c = Calendar.getInstance();
SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss aa");
String datetime = dateformat.format(c.getTime());
System.out.println(datetime);
To ge the current time you can use System.currentTimeMillis() which is standard in Java. Then you can use it to create a date
Date currentDate = new Date(System.currentTimeMillis());
And as mentioned by others to create a time
Time currentTime = new Time();
currentTime.setToNow();
You can use the code:
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(c.getTime());
Output:
2014-11-11 00:47:55
You also get some more formatting options for SimpleDateFormat from here.
Easy. You can dissect the time to get separate values for current time, as follows:
Calendar cal = Calendar.getInstance();
int millisecond = cal.get(Calendar.MILLISECOND);
int second = cal.get(Calendar.SECOND);
int minute = cal.get(Calendar.MINUTE);
// 12-hour format
int hour = cal.get(Calendar.HOUR);
// 24-hour format
int hourofday = cal.get(Calendar.HOUR_OF_DAY);
Same goes for the date, as follows:
Calendar cal = Calendar.getInstance();
int dayofyear = cal.get(Calendar.DAY_OF_YEAR);
int year = cal.get(Calendar.YEAR);
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
int dayofmonth = cal.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat databaseDateTimeFormate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat databaseDateFormate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf1 = new SimpleDateFormat("dd.MM.yy");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z");
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE, MMM d, ''yy");
SimpleDateFormat sdf4 = new SimpleDateFormat("h:mm a");
SimpleDateFormat sdf5 = new SimpleDateFormat("h:mm");
SimpleDateFormat sdf6 = new SimpleDateFormat("H:mm:ss:SSS");
SimpleDateFormat sdf7 = new SimpleDateFormat("K:mm a,z");
SimpleDateFormat sdf8 = new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm aaa");
String currentDateandTime = databaseDateTimeFormate.format(new Date()); //2009-06-30 08:29:36
String currentDateandTime = databaseDateFormate.format(new Date()); //2009-06-30
String currentDateandTime = sdf1.format(new Date()); //30.06.09
String currentDateandTime = sdf2.format(new Date()); //2009.06.30 AD at 08:29:36 PDT
String currentDateandTime = sdf3.format(new Date()); //Tue, Jun 30, '09
String currentDateandTime = sdf4.format(new Date()); //8:29 PM
String currentDateandTime = sdf5.format(new Date()); //8:29
String currentDateandTime = sdf6.format(new Date()); //8:28:36:249
String currentDateandTime = sdf7.format(new Date()); //8:29 AM,PDT
String currentDateandTime = sdf8.format(new Date()); //2009.June.30 AD 08:29 AM
Date format Patterns
G Era designator (before christ, after christ)
y Year (e.g. 12 or 2012). Use either yy or yyyy.
M Month in year. Number of M's determine length of format (e.g. MM, MMM or MMMMM)
d Day in month. Number of d's determine length of format (e.g. d or dd)
h Hour of day, 1-12 (AM / PM) (normally hh)
H Hour of day, 0-23 (normally HH)
m Minute in hour, 0-59 (normally mm)
s Second in minute, 0-59 (normally ss)
S Millisecond in second, 0-999 (normally SSS)
E Day in week (e.g Monday, Tuesday etc.)
D Day in year (1-366)
F Day of week in month (e.g. 1st Thursday of December)
w Week in year (1-53)
W Week in month (0-5)
a AM / PM marker
k Hour in day (1-24, unlike HH's 0-23)
K Hour in day, AM / PM (0-11)
z Time Zone
For the current date and time with format, use:
In Java
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(c.getTime());
Log.d("Date", "DATE: " + strDate)
In Kotlin
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy. HH:mm:ss")
var myDate: String = current.format(formatter)
Log.d("Date", "DATE: " + myDate)
} else {
var date = Date()
val formatter = SimpleDateFormat("MMM dd yyyy HH:mma")
val myDate: String = formatter.format(date)
Log.d("Date", "DATE: " + myDate)
}
Date formatter patterns
"yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
"hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
"EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
"yyMMddHHmmssZ"-------------------- 010704120856-0700
"K:mm a, z" ----------------------- 0:08 PM, PDT
"h:mm a" -------------------------- 12:08 PM
"EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
textView.setText("" + mDay + "-" + mMonth + "-" + mYear);
This is a method that will be useful to get date and time:
private String getDate(){
DateFormat dfDate = new SimpleDateFormat("yyyy/MM/dd");
String date=dfDate.format(Calendar.getInstance().getTime());
DateFormat dfTime = new SimpleDateFormat("HH:mm");
String time = dfTime.format(Calendar.getInstance().getTime());
return date + " " + time;
}
You can call this method and get the current date and time values:
2017/01//09 19:23
If you need the current date:
Calendar cc = Calendar.getInstance();
int year = cc.get(Calendar.YEAR);
int month = cc.get(Calendar.MONTH);
int mDay = cc.get(Calendar.DAY_OF_MONTH);
System.out.println("Date", year + ":" + month + ":" + mDay);
If you need the current time:
int mHour = cc.get(Calendar.HOUR_OF_DAY);
int mMinute = cc.get(Calendar.MINUTE);
System.out.println("time_format" + String.format("%02d:%02d", mHour , mMinute));
You can also use android.os.SystemClock.
For example SystemClock.elapsedRealtime() will give you more accurate time readings when the phone is asleep.
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);
Use:
Time time = new Time();
time.setToNow();
System.out.println("time: " + time.hour + ":" + time.minute);
This will give you, for example, "12:32".
Remember to import android.text.format.Time;.
You can simply use the following code:
DateFormat df = new SimpleDateFormat("HH:mm"); // Format time
String time = df.format(Calendar.getInstance().getTime());
DateFormat df1 = new SimpleDateFormat("yyyy/MM/dd"); // Format date
String date = df1.format(Calendar.getInstance().getTime());
Current time and date in Android with the format
Calendar c = Calendar.getInstance();
System.out.println("Current dateTime => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate = df.format(c.getTime());
System.out.println("Format dateTime => " + formattedDate);
Output
I/System.out: Current dateTime => Wed Feb 26 02:58:17 GMT+05:30 2020
I/System.out: Format dateTime => 26-02-2020 02:58:17 AM
For a customized time and date format:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ",Locale.ENGLISH);
String cDateTime = dateFormat.format(new Date());
The output is in this format:
2015-06-18T10:15:56-05:00
Time now = new Time();
now.setToNow();
Try this works for me as well.
You can obtain the date by using:
Time t = new Time(Time.getCurrentTimezone());
t.setToNow();
String date = t.format("%Y/%m/%d");
This will give you a result in a nice form, as in this example: "2014/02/09".
Well, I had problems with some answers by the API, so I fused this code:
Time t = new Time(Time.getCurrentTimezone());
t.setToNow();
String date1 = t.format("%Y/%m/%d");
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa", Locale.ENGLISH);
String var = dateFormat.format(date);
String horafecha = var+ " - " + date1;
tvTime.setText(horafecha);
Output:
03:25 PM - 2017/10/03
Java
Long date=System.currentTimeMillis();
SimpleDateFormat dateFormat =new SimpleDateFormat("dd / MMMM / yyyy - HH:mm", Locale.getDefault());
String dateStr = dateFormat.format(date);
Kotlin
date if milliseconds and 13 digits(hex to date)
val date=System.currentTimeMillis() //here the date comes in 13 digits
val dtlong = Date(date)
val sdfdate = SimpleDateFormat(pattern, Locale.getDefault()).format(dtlong)
Date Formatter
"dd / MMMM / yyyy - HH:mm" -> 29 / April / 2022 - 12:03
"dd / MM / yyyy" -> 29 / 03 / 2022
"dd / MMM / yyyy" -> 29 / Mar / 2022 (shortens the month)
"EEE, d MMM yyyy HH:mm:ss" -> Wed, 4 Jul 2022 12:08:56
Date todayDate = new Date();
todayDate.getDay();
todayDate.getHours();
todayDate.getMinutes();
todayDate.getMonth();
todayDate.getTime();
Try This
String mytime = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());
You should use the Calender class according to the new API. The Date class is deprecated now.
Calendar cal = Calendar.getInstance();
String date = "" + cal.get(Calendar.DATE) + "-" + (cal.get(Calendar.MONTH)+1) + "-" + cal.get(Calendar.YEAR);
String time = "" + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE);
The below method will return the current date and time in a String, Use a different time zone according to your actual time zone. I've used GMT.
public static String GetToday(){
Date presentTime_Date = Calendar.getInstance().getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
return dateFormat.format(presentTime_Date);
}
Related
Here is my date String "Thu Feb 25 12:58:28 MST 2016" and I parse using this formate "E MMM dd HH:mm:ss Z yyyy".
But I am getting date parsing error.
What should I do?
I am parsing date string using following function
public static String getDate(String targrtDate) {
String dateStr = targrtDate;
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = null;
try {
date = (Date) formatter.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date);
if (date == null) {
return "";
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
String formatedTime = cal.get(Calendar.HOUR) + "/" + cal.get(Calendar.MINUTE);
Log.i("formatedDate", "" + formatedDate + " " + formatedTime);
return formatedDate;
}
I have resolved my issue of date parsing.
If someone use MST timezone and if it gives an parsing error then please add second parameter of SimpleDateFormat() as
new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy", Locale.US);
So my final code will be
public static String getDate(String targrtDate) {
String dateStr = targrtDate;
SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy", Locale.US);
Date date = null;
try {
date = (Date) formatter.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date);
if (date == null) {
return "";
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
String formatedTime = cal.get(Calendar.HOUR) + ":" + cal.get(Calendar.MINUTE);
Log.i("formatedDate", "" + formatedDate + " " + formatedTime);
return formatedDate;
}
Special thanks to #MenoHochschild
tl;dr
ZonedDateTime.parse(
"Thu Feb 25 12:58:28 MST 2016" ,
DateTimeFormatter.ofPattern( "E MMM dd HH:mm:ss z uuuu" , Locale.US )
)
2016-02-25T12:58:28-07:00[America/Denver]
java.time
The modern approach uses the java.time classes. For Android, see last bullets below.
String input = "Thu Feb 25 12:58:28 MST 2016" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM dd HH:mm:ss z uuuu" , Locale.US ) ;
ZonedDateTime zdt = ZonedDateTime.parse( input , f ) ;
See this code run live at IdeOne.com. (But note that the JVM on that site is hard-wired to Locale.US, and any other is ignored.)
zdt.toString(): 2016-02-25T12:58:28-07:00[America/Denver]
Your input string is in a terrible format. If possible, change to using standard ISO 8601 formats. The standard formats are practical, easy to parse by machine and easy to read by humans across cultures. Conveniently, these formats are used by default in the java.time classes when parsing/generating strings.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as MST or EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId zEdmonton = ZoneId.of( "America/Edmonton" ) ;
ZoneId zDenver = ZoneId.of( "America/Denver" ) ;
ZoneId zMazatlan = ZoneId.of( "America/Mazatlan" ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
There are many questions like this on StackOverflow but no one has the answer I need. I have seen these 3 questions:
Get Value Of Day Month form Date Object in Android?
How to get month and day in android?
Get current time and date on Android
From these 3 questions I have learnt that to get date and time, we need to use Calendar. I have visited its documentation page but that is too hard to understand.
Now my question is I want to get current day i.e 12, current month i.e November, current year i.e 2014 and hour, minute, not seconds and AM or PM.
I only know till here:
Calendar c = Calendar.getInstance();
Now what should I do next?
You can customize the format you want using
DateFormat df = new SimpleDateFormat("dd MM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
Calendar calander = Calendar.getInstance();
cDay = calander.get(Calendar.DAY_OF_MONTH);
cMonth = calander.get(Calendar.MONTH) + 1;
cYear = calander.get(Calendar.YEAR);
selectedMonth = "" + cMonth;
selectedYear = "" + cYear;
cHour = calander.get(Calendar.HOUR);
cMinute = calander.get(Calendar.MINUTE);
cSecond = calander.get(Calendar.SECOND);
Use SimpleDateFormat to get date and time in desired format :
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd,MMMM,YYYY hh,mm,a");
String strDate = sdf.format(c.getTime());
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
Date currentTime = localCalendar.getTime();
int currentDay = localCalendar.get(Calendar.DATE);
int currentMonth = localCalendar.get(Calendar.MONTH) + 1;
int currentYear = localCalendar.get(Calendar.YEAR);
int currentDayOfWeek = localCalendar.get(Calendar.DAY_OF_WEEK);
int currentDayOfMonth = localCalendar.get(Calendar.DAY_OF_MONTH);
int CurrentDayOfYear = localCalendar.get(Calendar.DAY_OF_YEAR);
System.out.println("Current Date and time details in local timezone");
System.out.println("Current Date: " + currentTime);
System.out.println("Current Day: " + currentDay);
System.out.println("Current Month: " + currentMonth);
System.out.println("Current Year: " + currentYear);
System.out.println("Current Day of Week: " + currentDayOfWeek);
System.out.println("Current Day of Month: " + currentDayOfMonth);
System.out.println("Current Day of Year: " + CurrentDayOfYear);
tl;dr
I want to get current day i.e 12, current month i.e November, current year i.e 2014 and hour, minute, not seconds and AM or PM.
ZonedDateTime
.now(
ZoneId.of( "Pacific/Auckland" ) // Or "Asia/India", "Africa/Tunis", etc.
)
.format(
DateTimeFormatter
.ofPattern(
"dd MMMM uuuu HH:mm"
)
.withLocale(
Locale.CANADA_FRENCH // Or `Locale.US`, or `new Locale( "en" , "IN" )` for English language with India culture.
)
)
See this code run live at IdeOne.com.
28 septembre 2019 08:48
java.time
From these 3 questions I have learnt that to get date and time, we need to use Calendar.
Nope.
The Calendar class is terrible, along with Date & SimpleDateFormat and such. These classes were all supplanted years ago by the modern java.time classes defined in JSR 310.
Now my question is I want to get current day i.e 12, current month i.e November, current year i.e 2014 and hour, minute, not seconds and AM or PM.
Determining a date and time-of-day requires a time zone. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If you want to depend on the JVM’s current default time zone, make your intention clear by calling ZoneId.systemDefault(). If critical, confirm the zone with your user.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
Capture the current moment as seen in the wall-clock time used by the people of a certain region (a time zone).
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
If you do not care about the seconds or fractional-second, truncate.
ZonedDateTime zdt = ZonedDateTime.now( z ).truncatedTo( ChronoUnit.MINUTES ) ;
Generate a string in standard ISO 8601 format, wisely extended to append the name of the time zone in square brackets.
String output = zdt.toString() ;
2019-09-28T01:42+05:30[Asia/Kolkata]
Generate a string, automatically localized.
Locale locale = new Locale( "en" , "IN" ) ; // English language, India culture.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.LONG ).withLocale( locale ) ;
String output2 = zdt.format( f ) ;
28 September 2019 at 1:42:00 AM IST
See this code run live at IdeOne.com.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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);
}
}
Calendar calander = Calendar.getInstance();
cDay = calander.get(Calendar.DAY_OF_MONTH);
cMonth = calander.get(Calendar.MONTH) + 1;
cYear = calander.get(Calendar.YEAR);
selectedMonth = "" + cMonth;
selectedYear = "" + cYear;
cHour = calander.get(Calendar.HOUR);
cMinute = calander.get(Calendar.MINUTE);
cSecond = calander.get(Calendar.SECOND);
if i try the below code for eg:
i will set the date as Fri July 25 2014 10:00 AM. which gives date in milliseconds as 1402080056000,
now if i try to read the same milliseconds to date as below
long time = 1402080056000;
Date mydate = new Date(time);
mydate variable shows date as Sat Jun 25 00:10:56 IST 2014
String DateTimeString = DateFormat.getDateTimeInstance().format(new Date(time));
with the above statement in DateTimeString i get date as Jun 25 , 2014 12:10:56 AM
How to read the datetime present in 1402080056000 to Fri July 25 2014 10:00 AM
Just need to work on the format string,
String dateTimeString=
String.valueOf(new SimpleDateFormat("dd-MM-yyyy hh:mm").format(new Date(time)));
Explicitly set time zone:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String result = String.valueOf(dateFormat.format(millis));
Also, this would be useful Regarding Timezones and Java
try below code:
private String convertMilliToDate(long timestamp) {
DateFormat formatter = new SimpleDateFormat("YOUR DATE FORMAT");
// Create a calendar object that will convert the date and time value in
// milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
return formatter.format(calendar.getTime());
}
Try this:
String date= DateFormat.format("dd/MM/yyyy hh:mm:ss", new Date(date_in_milis)).toString();
Date-time work is easier using the Joda-Time library, which works on Android.
long millis = 1402080056000L;
DateTimeZone timeZoneIndia = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( millis, timeZoneIndia );
DateTime dateTimeFrance = dateTimeIndia.withZone( DateTimeZone.forID( "Europe/Paris" ) );
DateTime dateTimeUtc = dateTimeIndia.withZone( DateTimeZone.UTC );
To parse a string as a date-time, search StackOverflow for "Joda parse" to find many examples.
I am recieving the following long 1389967092 as a time stamp. This should represent ...
GMT: Fri, 17 Jan 2014 13:58:12 GMT
OR
My time zone: 1/17/2014 2:58:12 PM GMT+1
However I am in GMT+1 but the time I want to show is the GMT representation. I am trying the following:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeStamp);
Date date = cal.getTime();
Log.d(Point.class.getSimpleName(), date.getHours() + ":" + date.getMinutes());
But this prints 12:58
What am I doing wrong?
EDIT - RESPONSE TO ANSWER
This the code I am using it prints 1969-12-13 10:54:48
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(1389967092*1000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Log.d(Point.class.getSimpleName(), sdf.format(calendar.getTime));
The default Calendar.getInstance returns the time according to your device's timezone. However, you may request a different timezone like this:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
In order to print your current time according to different timezone(s) then you may use SimpleDateFormat. For example:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Log.d(TAG, sdf.format(new Date()));
I have seconds from epoch time and want to convert it to Day-Month-Year HH:MM
I have tried following but it gives me wrong value.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(seconds*1000);
String dateString = calendar.get(Calendar.DAY_OF_WEEK) + ", "+.......
Above code is not working properly am i doing anything wrong here.
For example if seconds = 1299671538
then it generates time string as Friday, December 12, 1969 which is wrong it should display Wednesday, March 09, 2011
For example if seconds = 1299671538 then it generates time string as Friday, December 12, 1969 which is wrong it should display Wednesday, March 09, 2011
You have integer overflow. Just use the following (notice "L" after 1000 constant):
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(seconds*1000L);
String dateString = calendar.get(Calendar.DAY_OF_WEEK) + ", "+.......
or better use SimpleDateFormat class:
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM d, yyyy HH:mm");
String dateString = formatter.format(new Date(seconds * 1000L));
this will give you the following date string for your original seconds input:
Wednesday, March 9, 2011 13:52
You need to use
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
instead of
Calendar cal = Calendar.getInstance();
because UTC time from seconds depends on Timezone.
You don't need a calendar in this case, you can simply use the constructor new Date(1000 * seconds)
Then use a SimpleDateFormat to create a String to display it.
For a full explanation on using SimpleDateFormat go here.
The answer to this question though is that you need to use long values instead of ints.
new Date(1299674566000l)
If you don't believe me, run this:
int secondsInt = 1299674566;
System.out.println(new Date(secondsInt *1000));
long secondsLong = 1299674566;
System.out.println(new Date(secondsLong *1000));
I can confirm that answer from #Idolon is working fine, simple snippet is below...
long created = 1300563523;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US);
String dateString = formatter.format(new Date(created * 1000L));
using SimpleDateFormat is better way, change the format as you need.
Won't it work wihtout Calendar, like below? Haven't run this piece of code, but guess it should work .
CharSequence theDate = DateFormat.format("Day-Month-Year HH:MM", objDate);