I am trying to parse date but I got timezone exception - android

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

Related

How to convert db2 date to YYYMMDD in 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.

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

Getting error java.text.ParseException: Unparseable date: (at offset 0) even if the Simple date format and string value are identical

I'm always getting the parse exception even if the format to check and the string value are same.
Here is the code:
String format = "EEE MMM dd HH:mm:ss z yyyy";
String value = "Mon Sep 18 10:30:06 MST 2017";
public static boolean isValidFormat(String format, String value) {
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.parse(value); // here it breaks
if (!value.equals(sdf.format(date))) {
date = null;
}
} catch (ParseException ex) {
ex.printStackTrace(); //java.text.ParseException: Unparseable date:
"Mon Sep 18 10:30:06 MST 2017" (at offset 0)
}
return date != null;
}
It says that your date-time string is unparseable at index 0. Index 0 is where it says Mon, so the three letter time zone abbreviation is not the first suspect. The locale is. “Mon” works as abbreviation for Monday in English, but not in very many other languages. So if your device has a non-English language setting — maybe it has even been changed recently — this will fully explain your observation.
The shortsighted solution is
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ROOT);
I use Locale.ROOT to mean that no language specific processing should be done. If your string is in English because English is generally the language used in computing around the globe, I would consider this choice appropriate. If on the other hand it is in English because it comes from an English speaking locale, that locale will be the right one to use.
With this change, on my computer your code formats your date into Mon Sep 18 11:30:06 MDT 2017, which, as you can see is not the same as the value we started out from, so your method returns false. My JVM understood MST as Mountain Standard Time, and then assumed summer time (DST) in September and formatted the string accordingly.
ThreeTenABP
That said, Date and SimpleDateFormat are long outdated classes. You should give it a thought to get rid of them and use the modern Java date and time API instead. On Android you get it in the ThreeTenABP, see this question: How to use ThreeTenABP in Android Project. Now you may do:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format, Locale.ROOT);
try {
return ZonedDateTime.parse(value, dtf).format(dtf).equals(value);
} catch (DateTimeParseException dtpe) {
dtpe.printStackTrace();
return false;
}
This behaves the same as above.
Three letter time zone abbreviations
You should avoid the three and four letter time zone abbreviations where you can. They are not standardized and generally ambiguous. MST, for example, may mean Malaysia Standard Time or Mountain Standard Time. The latter isn’t even a full time zone, since MDT is used for the greater part of the year, which caused the trouble I observed as I said above.
Instead, see if you can get a string in ISO 8601 format, like 2017-09-18T10:30:06+08:00. Second best, just get something unambiguous. One way is to include an offset from UTC rather than a time zone ID (or both).
Never use SimpleDateFormat or DateTimeFormatter without a Locale
Since the given date-time is in English, you should use Locale.ENGLISH with your date-time parser; otherwise the parsing will fail in a system (computer, phone etc.) which is using a non-English type of locale.
Also, note that the date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Demo:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
final String strDateTime = "Mon Sep 18 10:30:06 MST 2017";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM d H:m:s z uuuu", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
System.out.println(zdt);
}
}
Output:
2017-09-18T10:30:06-06:00[America/Denver]
An important note about timezone before we proceed further:
Avoid specifying a timezone with the 3-letter abbreviation. A timezone should be specified with a name in the format, Region/City e.g. ZoneId.of("Europe/London"). With this convention, the ZoneId for UTC can be specified with ZoneId.of("Etc/UTC"). A timezone specified in terms of UTC[+/-]Offset can be specified as Etc/GMT[+/-]Offset e.g. ZoneId.of("Etc/GMT+1"), ZoneId.of("Etc/GMT+1") etc.
There are some exceptional cases as well e.g. to specify the timezone of Turkey, we use
ZoneId.of("Turkey")
The following code will give you all the available ZoneIds:
// Get the set of all time zone IDs.
Set<String> allZones = ZoneId.getAvailableZoneIds();
You should ask your server application to provide you with the date-time using this convention e.g.
Mon Sep 18 10:30:06 America/Denver 2017
The above code, without any change, will work for this date-time string.
Coming back to the original topic:
By default, DateTimeFormatter#ofPattern uses the default FORMAT locale which the JVM sets during startup based on the host environment. Same is the case with SimpleDateFormat. I have tried to illustrate the problem through the following demo:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
final String strDateTime = "Mon Sep 18 10:30:06 America/Denver 2017";
DateTimeFormatter dtfWithDefaultLocale = null;
System.out.println("JVM's Locale: " + Locale.getDefault());
// Using DateTimeFormatter with the default Locale
dtfWithDefaultLocale = DateTimeFormatter.ofPattern("EEE MMM d H:m:s z uuuu");
System.out.println("DateTimeFormatter's Locale: " + dtfWithDefaultLocale.getLocale());
System.out
.println("Parsed with JVM's default locale: " + ZonedDateTime.parse(strDateTime, dtfWithDefaultLocale));
// Setting the JVM's default locale to Locale.FRANCE
Locale.setDefault(Locale.FRANCE);
// Using DateTimeFormatter with Locale.ENGLISH explicitly (recommended)
DateTimeFormatter dtfWithEnglishLocale = DateTimeFormatter.ofPattern("EEE MMM d H:m:s z uuuu", Locale.ENGLISH);
System.out.println("JVM's Locale: " + Locale.getDefault());
System.out.println("DateTimeFormatter's Locale: " + dtfWithEnglishLocale.getLocale());
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtfWithEnglishLocale);
System.out.println("Parsed with Locale.ENGLISH: " + zdt);
System.out.println("JVM's Locale: " + Locale.getDefault());
// Using DateTimeFormatter with the default Locale
dtfWithDefaultLocale = DateTimeFormatter.ofPattern("EEE MMM d H:m:s z uuuu");
System.out.println("DateTimeFormatter's Locale: " + dtfWithDefaultLocale.getLocale());
System.out
.println("Parsed with JVM's default locale: " + ZonedDateTime.parse(strDateTime, dtfWithDefaultLocale));
}
}
Output:
JVM's Locale: en_GB
DateTimeFormatter's Locale: en_GB
Parsed with JVM's default locale: 2017-09-18T10:30:06-06:00[America/Denver]
JVM's Locale: fr_FR
DateTimeFormatter's Locale: en
Parsed with Locale.ENGLISH: 2017-09-18T10:30:06-06:00[America/Denver]
JVM's Locale: fr_FR
DateTimeFormatter's Locale: fr_FR
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Mon Sep 18 10:30:06 America/Denver 2017' could not be parsed at index 0
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
at java.base/java.time.ZonedDateTime.parse(ZonedDateTime.java:598)
at Main.main(Main.java:32)
The following demo, using SimpleDateFormat, is just for the sake of completeness:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
final String strDateTime = "Mon Sep 18 10:30:06 MST 2017";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM d H:m:s z yyyy", Locale.ENGLISH);
Date date = sdf.parse(strDateTime);
System.out.println(date);
}
}
Output:
Mon Sep 18 18:30:06 BST 2017
Note: The java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970. When you print an object of java.util.Date, its toString method returns the date-time calculated from this milliseconds value. Since java.util.Date does not have timezone information, it applies the timezone of your JVM and displays the same. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFomrat and obtain the formatted string from it.
Here is the code of dateformatter which will hep you to convert your date into any time format.
public void setDate(String date) {
dateInput = (TextView) itemView.findViewById(R.id.dateText);
DateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
try {
dateData = inputFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
DateFormat outputFormat = new SimpleDateFormat("pur your desirable format");
String outputString = outputFormat.format(dateData);
dateInput.setText(outputString);
}
I use the almost use the same code as you do with only slight difference in SimpleDateFormat instantiation.
public static final String DATE_FORMAT = "EEE MMM d yyyy z HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.ROOT);
simpleDateFormat.format(date);
It returns Mon Sep 18 2017 GMT+03:00 23:04:10.

Parse a date-time string in ISO 8601 format without offset-from-UTC

I am parsing date of string type into Date format , but everytime got this exception
java.text.ParseException: Unparseable date: "2016-05-21T00:00:00" (at offset 4)
My code is :
String d = "2016-05-21T00:00:00";
DateFormat df = new SimpleDateFormat("yyyy MM dd HH:mm:ss", Locale.ENGLISH);
Date myDate = null;
try {
myDate = df.parse(d);
} catch (ParseException e) {
e.printStackTrace();
}
Your date string and DateFormat need to match. For your input "2016-05-21T00:00:00", the correct DateFormat is:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
tl;dr
LocalDateTime.parse( "2016-05-21T00:00:00" )
ISO 8601
The input string 2016-05-21T00:00:00 is in standard ISO 8601 format.
java.time
The java.time classes built into Java 8 and later use the ISO 8601 formats by default when parsing or generating textual representations of date-time values.
The input string lacks any offset-from-UTC or time zone info. So the string by itself is imprecise, has no specific meaning as it is not a moment on the timeline. Such values are represented in java.time by the LocalDateTime class.
String input = "2016-05-21T00:00:00";
LocalDateTime ldt = LocalDateTime.parse( input );
If you know from a larger context that the string is intended to have meaning for a certain offset-from-UTC, assign a ZoneOffset to get a OffsetDateTime object.
ZoneOffset zoneOffset = ZoneOffset.of( 5 , 30 );
OffsetDateTime odt = ldt.atOffset( zoneOffet );
Even better, if you are certain of an intended time zone, specify a ZoneId to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = ldt.atZone( ZoneId );
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
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
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
String expectedDateFormat=getDateFromString("2016-05-21 00:00:00","yyyy-MM-dd HH:mm:ss","yyyy MM dd HH:mm:ss");
This method will perform actual format to expected format.
public static String getDateFromString(String dateInString, String actualformat, String exceptedFormat) {
SimpleDateFormat form = new SimpleDateFormat(actualformat);
String formatedDate = null;
Date date;
try {
date = form.parse(dateInString);
SimpleDateFormat postFormater = new SimpleDateFormat(exceptedFormat);
formatedDate = postFormater.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return formatedDate;
}
public class test {
public static void main(String [] args) {
// ref http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");
System.out.println("Current Date: " + simpleDateFormat.format(new Date()));
}
}
for more information on SimpleDateFormat
try this way
String d = "2016-05-21 00:00:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
Date myDate = null;
try {
myDate = df.parse(d);
} catch (ParseException e) {
e.printStackTrace();
}
EDIT
String d = "2016-05-21 00:00:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
Date myDate = null;
try {
myDate = df.parse(d);
} catch (ParseException e) {
e.printStackTrace();
}

Categories

Resources