How to convert db2 date to YYYMMDD in android - android

I'm receiving a db2 date as 1200703 to the mobile as the response. I need to convert that date to a readable format as YYYYMMDD. How can I do that from the android side?

This is not db2 date format, but rather the way some systems store a date. It's so called CYYMMDD integer format.
YEAR = 1900 + 100*C + YY
MONTH = MM
DAY = DD

The date string, 1200703 is in CYYMMDD format. This format was (I'm not sure if it is still in use as the last time when I used DB2 was in 2008) used by DB2.
In order to calculate the year, you need to use the following formula:
Year = 100 * C + 1900 + YY e.g. for CYY = 120, the value of year = 100 * 1 + 1900 + 20 = 2020.
Once you convert the CYY part into yyyy format, you can use date-time formatting API as shown below:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class Main {
public static void main(String args[]) {
// Given date string
String dateStr = "1200703";
// Convert the given date string into yyyyMMdd format
int c = Integer.parseInt(dateStr.substring(0, 1));
int yy = Integer.parseInt(dateStr.substring(1, 3));
int year = 100 * c + 1900 + yy;
String dateStrConverted = String.valueOf(year) + dateStr.substring(3);
// ########## For Java 8 onwards ##############
// Define a formatter
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate localDate = LocalDate.parse(dateStrConverted, dtf);
System.out.println("Default format: " + localDate);
// Printing the date in a sample custom format
DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("EEE MMM dd yyyy");
String strDate1 = dtf1.format(localDate);
System.out.println(strDate1);
// ############################################
// ############## Before Java 8 ###############
// Define a formatter
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date utilDate = null;
try {
utilDate = sdf.parse(dateStrConverted);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Default format: " + utilDate);
// Printing the date in a sample custom format
SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd yyyy");
String strDate2 = sdf1.format(utilDate);
System.out.println(strDate2);
// ############################################
}
}
Output:
Default format: 2020-07-03
Fri Jul 03 2020
Default format: Fri Jul 03 00:00:00 BST 2020
Fri Jul 03 2020
Note: I recommend you use the modern date-time API. If the Android version which you are using is not compatible with Java-8, I suggest you backport using ThreeTen-Backport library. However, if you want to use the legacy API, you can use do so as shown in the answer.

Related

How to strip the year from the system/context/locale supplied DateFormat

I'd like to get the LocalDateTime string representation of a specific date.
Currently the supplied date is still an old java.util.Date Object. But the method should use modern LocalDate API.
What I'd like to achieve is a short representation of a given date in the users current locale.
I have three cases for this:
Same day: Display only the time in users locale format
Same year: Strip the year of the display but display the rest (Day, month and time)
Else: Display the whole date in users locale
I also would like the month to be written as Jan or Feb instead of 01 or 02 if this is still in harmony with the users locale.
My problem is: How can I strip the year from the context specific DateFormat and how can I get a locale date string where month is not 01 but Jan.
This is what i have right now:
public static String getLocaleDateTimeStringShort(Context context, Date date) {
if (date != null && context != null) {
//TODO: Display Jan instead 01
LocalDateTime ld = date.toInstant().atZone(ZoneOffset.UTC).toLocalDateTime();
LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC);
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context);
DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(context);
if(ld.getDayOfMonth()==now.getDayOfMonth() && ld.getMonthValue()==now.getMonthValue() && ld.getYear()==now.getYear()) {
//Same day
return timeFormat.format(date);
} else if(ld.getYear()==now.getYear()){
//Same year
/* TODO: Strip year from date */
//dateFormat.
}else{
return dateFormat.format(date) + " " + timeFormat.format(date);
}
}
return null;
}
UPDATE
I noticed there might be confusion as of what i want to achieve. Let's take a look at some examples:
Using locale of Germany (dd MMM yy HH:mm) and US (yy MMM dd HH:mm):
If something happens on the same day for both locale, i'd like to display the time without the date:
Germany:
11:33
States
11:33 am (if phone is in 12h mode)
11:33 (if phone is in 24h mode)
Now, the second case would be a date within the same year:
Germany:
29 Aug 11:33
States:
Aug 29 11:33
What happened here? The normal pattern for Germany is dd MMM yyyy and for the states yyyy MMM dd. Because the year is not needed if it is the same year we are in. I'd like the year to be stripped away.
Different year:
Germany:
30 Aug 19 11:33
States
19 Aug 30 11:33
(I am actually not sure if i used the correct datetimepattern for the states, but nevertheless i think you can see the point. I'd like to keep EVERYTHING from the locale specific Date/DateTime Pattern. But strip the date.
I even though StringManipulating it and remove all the "y" out of it
Another update:
You can remove the year part from the pattern in the following way:
public class Main {
public static void main(String[] args) {
// Test patterns
String[] patterns = { "MMM d, y, h:mm a", "d MMM y, HH:mm", "y年M月d日 ah:mm", "dd.MM.y, HH:mm", "y. M. d. a h:mm",
"d MMM y 'г'., HH:mm", "dd MMM y, HH:mm", "y/MM/dd H:mm", "d. MMM y, HH:mm", "dd‏/MM‏/y h:mm a",
"dd.M.y HH:mm", "d MMM y HH:mm" };
for (String pattern : patterns) {
System.out.println(pattern.replaceAll("([\\s,.\\/]\\s*)?y+[.\\/]?", "").trim());
}
}
}
Output:
MMM d, h:mm a
d MMM, HH:mm
年M月d日 ah:mm
dd.MM, HH:mm
M. d. a h:mm
d MMM 'г'., HH:mm
dd MMM, HH:mm
MM/dd H:mm
d. MMM, HH:mm
dd‏/MM‏ h:mm a
dd.M HH:mm
d MMM HH:mm
You can also check this for more explanation and a demo of the regex.
Explanation of the regex:
([\s,.\/]\s*)? specifies an optional group of a space, comma, dot or forward slash followed by any number of spaces
y+ specifies one or more y
[.\/]? specifies an optional dot or forward slash after y+
Update:
In the original answer, the date-time parts were fixed at specific locations in the pattern. I've written this update because OP has asked for the help to display locale-specific locations of date-time parts.
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.FormatStyle;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// A sample java.util.Date instance
Date date = new Date();
// Convert Date into LocalDateTime at UTC
LocalDateTime ldt = date.toInstant().atZone(ZoneOffset.UTC).toLocalDateTime();
// Instantiate Locale with the default locale
Locale locale = Locale.getDefault();
// Build a pattern for date
String datePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM, null,
IsoChronology.INSTANCE, locale);
// Build a pattern for time
String timePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(null, FormatStyle.MEDIUM,
IsoChronology.INSTANCE, locale);
// Build a pattern for date and time
String dateTimePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM,
FormatStyle.MEDIUM, IsoChronology.INSTANCE, locale);
System.out.println("Test reslts for my default locale:");
System.out.println(ldt.format(DateTimeFormatter.ofPattern(datePattern, locale)));
System.out.println(ldt.format(DateTimeFormatter.ofPattern(timePattern, locale)));
System.out.println(ldt.format(DateTimeFormatter.ofPattern(dateTimePattern, locale)));
// Let's test it for the Locale.GERMANY
locale = Locale.GERMANY;
System.out.println("\nTest reslts for Locale.GERMANY:");
String datePatternGermany = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM, null,
IsoChronology.INSTANCE, locale);
String timePatternGermany = DateTimeFormatterBuilder.getLocalizedDateTimePattern(null, FormatStyle.MEDIUM,
IsoChronology.INSTANCE, locale);
String dateTimePatternGermany = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM,
FormatStyle.MEDIUM, IsoChronology.INSTANCE, locale);
System.out.println(ldt.format(DateTimeFormatter.ofPattern(datePatternGermany, locale)));
System.out.println(ldt.format(DateTimeFormatter.ofPattern(timePatternGermany, locale)));
System.out.println(ldt.format(DateTimeFormatter.ofPattern(dateTimePatternGermany, locale)));
// Let's test it for the Locale.US
locale = Locale.US;
System.out.println("\nTest reslts for Locale.US:");
String datePatternUS = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM, null,
IsoChronology.INSTANCE, locale);
String timePatternUS = DateTimeFormatterBuilder.getLocalizedDateTimePattern(null, FormatStyle.MEDIUM,
IsoChronology.INSTANCE, locale);
String dateTimePatternUS = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM,
FormatStyle.MEDIUM, IsoChronology.INSTANCE, locale);
System.out.println(ldt.format(DateTimeFormatter.ofPattern(datePatternUS, locale)));
System.out.println(ldt.format(DateTimeFormatter.ofPattern(timePatternUS, locale)));
System.out.println(ldt.format(DateTimeFormatter.ofPattern(dateTimePatternUS, locale)));
}
}
Output:
Test reslts for my default locale:
30 Aug 2020
09:24:04
30 Aug 2020, 09:24:04
Test reslts for Locale.GERMANY:
30.08.2020
09:24:04
30.08.2020, 09:24:04
Test reslts for Locale.US:
Aug 30, 2020
9:24:04 AM
Aug 30, 2020, 9:24:04 AM
Original answer:
The following code has all that you need as per your question:
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// A sample java.util.Date instance
Date date = new Date();
// Convert Date into LocalDateTime at UTC
LocalDateTime ldt = date.toInstant().atZone(ZoneOffset.UTC).toLocalDateTime();
// Get the string representing just time part
String sameDayDateTime = ldt.format(DateTimeFormatter.ofPattern("HH:mm:ss", Locale.getDefault()));
System.out.println(sameDayDateTime);
// Get the string representing all parts except year
String sameYearDateTime = ldt.format(DateTimeFormatter.ofPattern("MMM dd, HH:mm:ss", Locale.getDefault()));
System.out.println(sameYearDateTime);
// Display the default string representation of the date-time
String defaultDateTimeStr = ldt.toString();
System.out.println(defaultDateTimeStr);
// Display the string representation of the date-time in custom format
String customDateTimeStr = ldt
.format(DateTimeFormatter.ofPattern("yyyy MMM dd, HH:mm:ss", Locale.getDefault()));
System.out.println(customDateTimeStr);
}
}
Output:
21:37:24
Aug 28, 21:37:24
2020-08-28T21:37:24.697
2020 Aug 28, 21:37:24
Since you want to be able to format/parse without year, you cannot use the built-in localized formats, you have to build your own format patterns.
Since some parts are optional, you need 3 patterns (full, without year, and without date). The full pattern can be re-used for parsing, by defining optional sections, and supplying the optional values using parseDefaulting().
First, here is a map defining some date/time format pattern for some locales, and a helper method for getting a particular pattern:
private static final Map<Locale, List<String>> FORMATS = Map.of(
Locale.ENGLISH , List.of("[MMM d[, uuuu], ]h:mm a", "MMM d, h:mm a", "h:mm a"),
Locale.FRENCH , List.of("[d MMM[ uuuu] ]HH:mm" , "d MMM HH:mm" , "HH:mm" ),
Locale.GERMAN , List.of("[dd.MM[.uuuu], ]HH:mm" , "dd.MM, HH:mm" , "HH:mm" ),
Locale.JAPANESE, List.of("[[uuuu/]MM/dd ]H:mm" , "MM/dd H:mm" , "H:mm" )
);
private static String getFormat(Locale locale, int index) {
List<String> formats = FORMATS.get(locale);
if (formats == null)
throw new IllegalArgumentException("Format patterns not available for locale " + locale.toLanguageTag());
return formats.get(index);
}
Map.of() and List.of() were both added in Java 9, and is used here for convenience.
To format a LocalDateTime, use this method:
static String format(LocalDateTime dateTime, Locale locale) {
LocalDate today = LocalDate.now();
if (dateTime.toLocalDate().equals(today))
return dateTime.format(DateTimeFormatter.ofPattern(getFormat(locale, 2), locale));
if (dateTime.getYear() == today.getYear())
return dateTime.format(DateTimeFormatter.ofPattern(getFormat(locale, 1), locale));
return dateTime.format(DateTimeFormatter.ofPattern(getFormat(locale, 0), locale));
}
To parse a formatted string back into a LocalDateTime, use this method, which uses the parseDefaulting() to supply today's date as default values:
static LocalDateTime parse(String dateTime, Locale locale) {
LocalDate today = LocalDate.now();
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern(getFormat(locale, 0))
.parseDefaulting(ChronoField.YEAR, today.getYear())
.parseDefaulting(ChronoField.MONTH_OF_YEAR, today.getMonthValue())
.parseDefaulting(ChronoField.DAY_OF_MONTH, today.getDayOfMonth())
.toFormatter(locale);
return LocalDateTime.parse(dateTime, formatter);
}
Test
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
FORMATS.keySet().stream().sorted(Comparator.comparing(Locale::getDisplayLanguage)).forEachOrdered(locale -> {
System.out.println(locale.getDisplayLanguage() + ":");
test(now.minusYears(1), locale);
test(now.minusDays(1), locale);
test(now, locale);
});
}
private static void test(LocalDateTime dateTime, Locale locale) {
String formatted = format(dateTime, locale);
LocalDateTime parsed = parse(formatted, locale);
System.out.printf(" %s formats to %-23s and parses back to %s%n", dateTime, formatted, parsed);
}
The stream is just used as a convenient way to sort the output.
Output
English:
2019-08-30T08:20:59.126394500 formats to Aug 30, 2019, 8:20 AM and parses back to 2019-08-30T08:20
2020-08-29T08:20:59.126394500 formats to Aug 29, 8:20 AM and parses back to 2020-08-29T08:20
2020-08-30T08:20:59.126394500 formats to 8:20 AM and parses back to 2020-08-30T08:20
French:
2019-08-30T08:20:59.126394500 formats to 30 août 2019 08:20 and parses back to 2019-08-30T08:20
2020-08-29T08:20:59.126394500 formats to 29 août 08:20 and parses back to 2020-08-29T08:20
2020-08-30T08:20:59.126394500 formats to 08:20 and parses back to 2020-08-30T08:20
German:
2019-08-30T08:20:59.126394500 formats to 30.08.2019, 08:20 and parses back to 2019-08-30T08:20
2020-08-29T08:20:59.126394500 formats to 29.08, 08:20 and parses back to 2020-08-29T08:20
2020-08-30T08:20:59.126394500 formats to 08:20 and parses back to 2020-08-30T08:20
Japanese:
2019-08-30T08:20:59.126394500 formats to 2019/08/30 8:20 and parses back to 2019-08-30T08:20
2020-08-29T08:20:59.126394500 formats to 08/29 8:20 and parses back to 2020-08-29T08:20
2020-08-30T08:20:59.126394500 formats to 8:20 and parses back to 2020-08-30T08:20

How to present timestamp date retrieved from firestore in a nice format [duplicate]

How to format correctly according to the device configuration date and time when having a year, month, day, hour and minute?
Use the standard Java DateFormat class.
For example to display the current date and time do the following:
Date date = new Date(location.getTime());
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));
You can initialise a Date object with your own values, however you should be aware that the constructors have been deprecated and you should really be using a Java Calendar object.
In my opinion, android.text.format.DateFormat.getDateFormat(context) makes me confused because this method returns java.text.DateFormat rather than android.text.format.DateFormat - -".
So, I use the fragment code as below to get the current date/time in my format.
android.text.format.DateFormat df = new android.text.format.DateFormat();
df.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());
or
android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());
In addition, you can use others formats. Follow DateFormat.
You can use DateFormat. Result depends on default Locale of the phone, but you can specify Locale too :
https://developer.android.com/reference/java/text/DateFormat.html
This is results on a
DateFormat.getDateInstance().format(date)
FR Locale : 3 nov. 2017
US/En Locale : Jan 12, 1952
DateFormat.getDateInstance(DateFormat.SHORT).format(date)
FR Locale : 03/11/2017
US/En Locale : 12.13.52
DateFormat.getDateInstance(DateFormat.MEDIUM).format(date)
FR Locale : 3 nov. 2017
US/En Locale : Jan 12, 1952
DateFormat.getDateInstance(DateFormat.LONG).format(date)
FR Locale : 3 novembre 2017
US/En Locale : January 12, 1952
DateFormat.getDateInstance(DateFormat.FULL).format(date)
FR Locale : vendredi 3 novembre 2017
US/En Locale : Tuesday, April 12, 1952
DateFormat.getDateTimeInstance().format(date)
FR Locale : 3 nov. 2017 16:04:58
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(date)
FR Locale : 03/11/2017 16:04
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).format(date)
FR Locale : 03/11/2017 16:04:58
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(date)
FR Locale : 03/11/2017 16:04:58 GMT+01:00
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL).format(date)
FR Locale : 03/11/2017 16:04:58 heure normale d’Europe centrale
DateFormat.getTimeInstance().format(date)
FR Locale : 16:04:58
DateFormat.getTimeInstance(DateFormat.SHORT).format(date)
FR Locale : 16:04
DateFormat.getTimeInstance(DateFormat.MEDIUM).format(date)
FR Locale : 16:04:58
DateFormat.getTimeInstance(DateFormat.LONG).format(date)
FR Locale : 16:04:58 GMT+01:00
DateFormat.getTimeInstance(DateFormat.FULL).format(date)
FR Locale : 16:04:58 heure normale d’Europe centrale
Date to Locale date string:
Date date = new Date();
String stringDate = DateFormat.getDateTimeInstance().format(date);
Options:
DateFormat.getDateInstance()
- > Dec 31, 1969
DateFormat.getDateTimeInstance()
-> Dec 31, 1969 4:00:00 PM
DateFormat.getTimeInstance()
-> 4:00:00 PM
This will do it:
Date date = new Date();
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));
Date and Time format explanation
EEE : Day ( Mon )
MMMM : Full month name ( December ) // MMMM February
MMM : Month in words ( Dec )
MM : Month ( 12 )
dd : Day in 2 chars ( 03 )
d: Day in 1 char (3)
HH : Hours ( 12 )
mm : Minutes ( 50 )
ss : Seconds ( 34 )
yyyy: Year ( 2020 ) //both yyyy and YYYY are same
YYYY: Year ( 2020 )
zzz : GMT+05:30
a : ( AM / PM )
aa : ( AM / PM )
aaa : ( AM / PM )
aaaa : ( AM / PM )
Use SimpleDateFormat
Like this:
event.putExtra("starttime", "12/18/2012");
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date date = format.parse(bundle.getString("starttime"));
Here is the simplest way:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.US);
String time = df.format(new Date());
and If you are looking for patterns, check this
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Following this: http://developer.android.com/reference/android/text/format/Time.html
Is better to use Android native Time class:
Time now = new Time();
now.setToNow();
Then format:
Log.d("DEBUG", "Time "+now.format("%d.%m.%Y %H.%M.%S"));
Use these two as a class variables:
public java.text.DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
private Calendar mDate = null;
And use it like this:
mDate = Calendar.getInstance();
mDate.set(year,months,day);
dateFormat.format(mDate.getTime());
This is my method, you can define and input and output format.
public static String formattedDateFromString(String inputFormat, String outputFormat, String inputDate){
if(inputFormat.equals("")){ // if inputFormat = "", set a default input format.
inputFormat = "yyyy-MM-dd hh:mm:ss";
}
if(outputFormat.equals("")){
outputFormat = "EEEE d 'de' MMMM 'del' yyyy"; // if inputFormat = "", set a default output format.
}
Date parsed = null;
String outputDate = "";
SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, java.util.Locale.getDefault());
SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, java.util.Locale.getDefault());
// You can set a different Locale, This example set a locale of Country Mexico.
//SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, new Locale("es", "MX"));
//SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, new Locale("es", "MX"));
try {
parsed = df_input.parse(inputDate);
outputDate = df_output.format(parsed);
} catch (Exception e) {
Log.e("formattedDateFromString", "Exception in formateDateFromstring(): " + e.getMessage());
}
return outputDate;
}
SimpleDateFormat
I use SimpleDateFormat without custom pattern to get actual date and time from the system in the device's preselected format:
public static String getFormattedDate() {
//SimpleDateFormat called without pattern
return new SimpleDateFormat().format(Calendar.getInstance().getTime());
}
returns:
13.01.15 11:45
1/13/15 10:45 AM
...
Use build in Time class!
Time time = new Time();
time.set(0, 0, 17, 4, 5, 1999);
Log.i("DateTime", time.format("%d.%m.%Y %H:%M:%S"));
This code work for me!
Date d = new Date();
CharSequence s = android.text.format.DateFormat.format("MM-dd-yy hh-mm-ss",d.getTime());
Toast.makeText(this,s.toString(),Toast.LENGTH_SHORT).show();
Shortest way:
// 2019-03-29 16:11
String.format("%1$tY-%<tm-%<td %<tR", Calendar.getInstance())
%tR is short for %tH:%tM, < means to reuse last parameter(1$).
It is equivalent to String.format("%1$tY-%1$tm-%1$td %1$tH:%1$tM", Calendar.getInstance())
https://developer.android.com/reference/java/util/Formatter.html
Date format class work with cheat code to make date. Like
M -> 7, MM -> 07, MMM -> Jul , MMMM -> July
EEE -> Tue , EEEE -> Tuesday
z -> EST , zzz -> EST , zzzz -> Eastern Standard Time
You can check more cheats here.
The other answers are generally correct. I should like to contribute the modern answer. The classes Date, DateFormat and SimpleDateFormat used in most of the other answers, are long outdated and have caused trouble for many programmers over many years. Today we have so much better in java.time, AKA JSR-310, the modern Java date & time API. Can you use this on Android yet? Most certainly! The modern classes have been backported to Android in the ThreeTenABP project. See this question: How to use ThreeTenABP in Android Project for all the details.
This snippet should get you started:
int year = 2017, month = 9, day = 28, hour = 22, minute = 45;
LocalDateTime dateTime = LocalDateTime.of(year, month, day, hour, minute);
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
System.out.println(dateTime.format(formatter));
When I set my computer’s preferred language to US English or UK English, this prints:
Sep 28, 2017 10:45:00 PM
When instead I set it to Danish, I get:
28-09-2017 22:45:00
So it does follow the configuration. I am unsure exactly to what detail it follows your device’s date and time settings, though, and this may vary from phone to phone.
This code would return the current date and time:
public String getCurrDate()
{
String dt;
Date cal = Calendar.getInstance().getTime();
dt = cal.toLocaleString();
return dt;
}
I use it like this:
public class DateUtils {
static DateUtils instance;
private final DateFormat dateFormat;
private final DateFormat timeFormat;
private DateUtils() {
dateFormat = android.text.format.DateFormat.getDateFormat(MainApplication.context);
timeFormat = android.text.format.DateFormat.getTimeFormat(MainApplication.context);
}
public static DateUtils getInstance() {
if (instance == null) {
instance = new DateUtils();
}
return instance;
}
public synchronized static String formatDateTime(long timestamp) {
long milliseconds = timestamp * 1000;
Date dateTime = new Date(milliseconds);
String date = getInstance().dateFormat.format(dateTime);
String time = getInstance().timeFormat.format(dateTime);
return date + " " + time;
}
}
Locale
To get date or time in locale format from milliseconds I used this:
Date and time
Date date = new Date(milliseconds);
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault());
dateFormat.format(date);
Date
Date date = new Date(milliseconds);
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault());
dateFormat.format(date);
Time
Date date = new Date(milliseconds);
DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
dateFormat.format(date);
You can use other date style and time style. More info about styles here.
Try:
event.putExtra("startTime", "10/05/2012");
And when you are accessing passed variables:
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(bundle.getString("startTime"));
Avoid j.u.Date
The Java.util.Date and .Calendar and SimpleDateFormat in Java (and Android) are notoriously troublesome. Avoid them. They are so bad that Sun/Oracle gave up on them, supplanting them with the new java.time package in Java 8 (not in Android as of 2014). The new java.time was inspired by the Joda-Time library.
Joda-Time
Joda-Time does work in Android.
Search StackOverflow for "Joda" to find many examples and much discussion.
A tidbit of source code using Joda-Time 2.4.
Standard format.
String output = DateTime.now().toString();
// Current date-time in user's default time zone with a String representation formatted to the ISO 8601 standard.
Localized format.
String output = DateTimeFormat.forStyle( "FF" ).print( DateTime.now() );
// Full (long) format localized for this user's language and culture.
Back to 2016, When I want to customize the format (not according to the device configuration, as you ask...) I usually use the string resource file:
in strings.xml:
<string name="myDateFormat"><xliff:g id="myDateFormat">%1$td/%1$tm/%1$tY</xliff:g></string>
In Activity:
Log.d(TAG, "my custom date format: "+getString(R.string.myDateFormat, new Date()));
This is also useful with the release of the new Date Binding Library.
So I can have something like this in layout file:
<TextView
android:id="#+id/text_release_date"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:padding="2dp"
android:text="#{#string/myDateFormat(vm.releaseDate)}"
tools:text="0000"
/>
And in java class:
MovieDetailViewModel vm = new MovieDetailViewModel();
vm.setReleaseDate(new Date());
The android Time class provides 3 formatting methods http://developer.android.com/reference/android/text/format/Time.html
This is how I did it:
/**
* This method will format the data from the android Time class (eg. myTime.setToNow()) into the format
* Date: dd.mm.yy Time: hh.mm.ss
*/
private String formatTime(String time)
{
String fullTime= "";
String[] sa = new String[2];
if(time.length()>1)
{
Time t = new Time(Time.getCurrentTimezone());
t.parse(time);
// or t.setToNow();
String formattedTime = t.format("%d.%m.%Y %H.%M.%S");
int x = 0;
for(String s : formattedTime.split("\\s",2))
{
System.out.println("Value = " + s);
sa[x] = s;
x++;
}
fullTime = "Date: " + sa[0] + " Time: " + sa[1];
}
else{
fullTime = "No time data";
}
return fullTime;
}
I hope thats helpful :-)
It's too late but it may help to someone
DateFormat.format(format, timeInMillis);
here format is what format you need
ex: "HH:mm" returns 15:30
Date from type
EEE : Day ( Mon )
MMMM : Full month name ( December ) // MMMM February
MMM : Month in words ( Dec )
MM : Month ( 12 )
dd : Day in 2 chars ( 03 )
d: Day in 1 char (3)
HH : Hours ( 12 )
mm : Minutes ( 50 )
ss : Seconds ( 34 )
yyyy: Year ( 2022 ) //both yyyy and YYYY are same
YYYY: Year ( 2022 )
zzz : GMT+05:30
a : ( AM / PM )
aa : ( AM / PM )
aaa : ( AM / PM )
aaaa : ( AM / PM )

Check to see if current time is 00:00:00 [duplicate]

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);
}

I am trying to parse date but I got timezone exception

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….

Android date parsing (Extracting month and year )

I want my app to parse the date in format "dd-MMM-yyyy". The date has been successfully parsed when I try to get month and get year it is giving other result. I inpued 06-sep-2014 as date. But when I try to extract month and year from the parsed date it is showing 8 for month instead of 9 and 114 for year instead of 2014.
logcat output
6
8
114
Here's my code
String date1 = "06 sep 2014";
SimpleDateFormat format1 = new SimpleDateFormat("dd MMM yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("d MMM yyyy");
Date date;
try {
if (date1.length() == 11) {
date = format1.parse(date1);
} else {
date = format2.parse(date1);
}
int day=date.getDate();
int mon1=date.getMonth();
int year1=date.getYear();
System.out.println("date is:"+ date);
System.out.println(day);
System.out.println(mon1);
System.out.println(year1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public final class DateParseDemo {
public static void main(String[] args){
final DateFormat df = new SimpleDateFormat("dd MMM yyyy");
final Calendar c = Calendar.getInstance();
try {
c.setTime(df.parse("06 sep 2014"));
System.out.println("Year = " + c.get(Calendar.YEAR));
System.out.println("Month = " + (c.get(Calendar.MONTH)));
System.out.println("Day = " + c.get(Calendar.DAY_OF_MONTH));
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
Output:
Year = 2014
Month = 8
Day = 6
And as for the month field, this is 0-based. This means that January = 0 and December = 11. As stated by the javadoc,
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
Because date.getyear Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
Maybe, You can use for example;
int year1=date.getYear();
System.out.println(year1+1900);
Using the Date class, it gives you the year starting from 1900. A better way to get what you want is using the Calendar class. See http://developer.android.com/reference/java/util/Date.html#getYear()

Categories

Resources