Android: How can I Convert String to Date? - android

I store current time in database each time application starts by user.
Calendar c = Calendar.getInstance();
String str = c.getTime().toString();
Log.i("Current time", str);
In database side, I store current time as string (as you see in above code). Therefore, when I load it from database, I need to cast it to Date object. I saw some samples that all of them had used "DateFormat". But my format is exactly as same as Date format. So, I think there is no need to use "DateFormat". Am I right?
Is there anyway to directly cast this String to Date object? I want to compare this stored time with current time.
update
Thanks all. I used following code:
private boolean isPackageExpired(String date){
boolean isExpired=false;
Date expiredDate = stringToDate(date, "EEE MMM d HH:mm:ss zz yyyy");
if (new Date().after(expiredDate)) isExpired=true;
return isExpired;
}
private Date stringToDate(String aDate,String aFormat) {
if(aDate==null) return null;
ParsePosition pos = new ParsePosition(0);
SimpleDateFormat simpledateformat = new SimpleDateFormat(aFormat);
Date stringDate = simpledateformat.parse(aDate, pos);
return stringDate;
}

From String to Date
String dtStart = "2010-10-15T09:27:37Z";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = format.parse(dtStart);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
From Date to String
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = new Date();
String dateTime = dateFormat.format(date);
System.out.println("Current Date Time : " + dateTime);
} catch (ParseException e) {
e.printStackTrace();
}

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date d = dateFormat.parse(datestring)

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyClass
{
public static void main(String args[])
{
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
String dateInString = "Wed Mar 14 15:30:00 EET 2018";
SimpleDateFormat formatterOut = new SimpleDateFormat("dd MMM yyyy");
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatterOut.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
here is your Date object date
and the output is :
Wed Mar 14 13:30:00 UTC 2018
14 Mar 2018

using SimpleDateFormat or DateFormat class through
for e.g.
try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
// handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}

You can use java.time in Android now, either by using Android API Desugaring or importing the ThreeTenAbp.
With java.time enabled, you can do the same operations with less code and less errors.
Let's assume you are passing a String containing a datetime formatted in ISO standard, just as the currently accepted answer does.
Then the following methods and their usage in a main may show you how to convert from and to String:
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
ZonedDateTime odt = convert(dtStart);
System.out.println(odt);
}
and
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
OffsetDateTime odt = convert(dtStart);
System.out.println(odt);
}
will print the line
2010-10-15T09:27:37Z
when there are the corresponding methods
public static OffsetDateTime convert(String datetime) {
return OffsetDateTime.parse(datetime);
}
or
public static ZonedDateTime convert(String datetime) {
return ZonedDateTime.parse(datetime);
}
but of course not in the same class, that would not compile...
There's a LocalDateTime, too, but that would not be able to parse a zone or offset.
If you want to use custom formats for parsing or formatting output, you can utilize a DateTimeFormatter, maybe like this:
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
String converted = ZonedDateTime.parse(dtStart)
.format(DateTimeFormatter.ofPattern(
"EEE MMM d HH:mm:ss zz uuuu",
Locale.ENGLISH
)
);
System.out.println(converted);
}
which will output
Fri Oct 15 09:27:37 Z 2010
For an OffsetDateTime, you would need to adjust the pattern a little:
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
String converted = OffsetDateTime.parse(dtStart)
.format(DateTimeFormatter.ofPattern(
"EEE MMM d HH:mm:ss xxx uuuu",
Locale.ENGLISH
)
);
System.out.println(converted);
}
This will produce a (slightly) different output:
Fri Oct 15 09:27:37 +00:00 2010
That's because a ZonedDateTime considers named time zones with changing offsets (due to daylight saving times or anything similar) while an OffsetDateTime just knows an offset from UTC.

It could be a good idea to be careful with the Locale upon which c.getTime().toString(); depends.
One idea is to store the time in seconds (e.g. UNIX time). As an int you can easily compare it, and then you just convert it to string when displaying it to the user.

String source = "24/10/17";
String[] sourceSplit= source.split("/");
int anno= Integer.parseInt(sourceSplit[2]);
int mese= Integer.parseInt(sourceSplit[1]);
int giorno= Integer.parseInt(sourceSplit[0]);
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(anno,mese-1,giorno);
Date data1= calendar.getTime();
SimpleDateFormat myFormat = new SimpleDateFormat("20yy-MM-dd");
String dayFormatted= myFormat.format(data1);
System.out.println("data formattata,-->"+dayFormatted);

Related

Android - Getting different UTC time

I have two methods for get UTC date time.
method:1) get current UTC
public static String getUTCdatetimeAsString()
{
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd- HH:mm:ss", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
Log.e("utcTime : " ,""+ utcTime);
return utcTime;
}
which print below Log
utcTime : 2018-07-12- 12:37:09
method:2) select date from calendar and get UTC
public static String dateUTCToLocal() {
try {
SimpleDateFormat formatter = new SimpleDateFormat("d/M/yyyy HH:mm:ss", Locale.US);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse("12/7/2018 06:07:09");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd- HH:mm:ss", Locale.US);
format.setTimeZone(TimeZone.getDefault());
return format.format(value);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
which print below Log
2018-07-12- 11:37:09
Problem : getting different UTC date (1 hour different )not understand why i tried many solutions but not getting perfect result, any help appreciate thanks in advance.
Try this format ..
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd- HH:mm:ss a", Locale.US);
it show time into am pm wise.
The line "format.setTimeZone(TimeZone.getDefault());" sets the timezone you are currently in while "sdf.setTimeZone(TimeZone.getTimeZone("UTC"));" sets the timezone to "UTC". You should stick with the second line if you want to get UTC-time

How to convert Java.Util.Date to System.DateTime

In Xamarin.Android, you work with both .NET and Java.
I get a return value of Java.Util.Date, I then need to input that same value as a parameter that only takes System.DateTime
This is how I currently do it
public static DateTime ConvertJavaDateToDateTime(Date date)
{
var a = date.ToGMTString();
var b = date.ToLocaleString();
var c = date.ToString();
DateTime datetime = DateTime.ParseExact(date.ToGMTString(), "dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture);
return datetime;
}
However on the first 9 days of any month, I only get 1 digit for the day, and the
DateTime.ParseExact function is looking for dd (i.e. 2 digits for the day).
a is a string with value "1 Sep 2014 14:32:25 GMT"
b is a string with value "1 Sep 2014 16:32:25"
c is a string with value "Mon Sep 01 16:32:25 EET 2014"
I wish I could find a simple, quick, reliable and consistent solution for this problem :D
java.util.Date has a getTime() method, which returns the date as a millisecond value. The value is the number of milliseconds since Jan. 1, 1970, midnight GMT.
With that knowledge, you can construct a System.DateTime, that matches this value like so:
public DateTime FromUnixTime(long unixTimeMillis)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddMilliseconds(unixTimeMillis);
}
(method taken from this answer)
Do this:
public DateTime ConvertDateToDateTime(Date date)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
String dateFormated = dateFormat.format(date);
return new DateTime(dateFormated);
}
I'll update my answer, since you've changed the question.
you can use a long to hold the milliseconds and than convert the milliseconds to ticks(x10000) and create a new DateTime
Date date = new Date();
Long milliseconds = date.getTime();
Long ticks = milliseconds * 10000
DateTime datetime = DateTime(ticks);
I had this problem when authenticating with Facebook to receive the Expire time for the token. The solution was to do this:
var convertedTime = new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc).AddMilliseconds(MyJavaUtil.Date.Time);
I used this:
DateTimeOffset.FromUnixTimeMilliseconds(date.Time - (date.TimezoneOffset * 60 * 1000)).DateTime;
To incorporate the timezone offset into my date.
In my case, only this code works correctly:
public static DateTime NativeDateToDateTime(Java.Util.Date date)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
string dateFormated = dateFormat.Format(date);
return DateTimeOffset.Parse(dateFormated, null, DateTimeStyles.None).DateTime;
}
It is not tested but try with Calendar methods
public static String ConvertJavaDateToDateTime(Date date)
{
Calendar c = new GregorianCalendar();
c.setTime(date);
System.out.println(c.getTime());
return c.getTime();
}
Prints:
Tue Aug 06 00:00:00 EDT 2013
You can try with this also
public DateTime dateAndTimeToDateTime(java.sql.Date date, java.sql.Time time) {
String myDate = date + " " + time;
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss 'GMT'");
java.util.Date utilDate = new java.util.Date();
try {
utilDate = sdf.parse(myDate);
} catch (ParseException pe){
pe.printStackTrace();
}
DateTime dateTime = new DateTime(utilDate);
return dateTime;
}

Datetime conversion one timezone to another timezone in Android

I stuck with timezone conversion can any one help me to get out of it
My code for time conversion is below
public static String convertToLocalTimeZone(String date, String timeZone)
{
SimpleDateFormat df1 = new SimpleDateFormat("MM/dd/yyyy HH:mm a");
df1.setTimeZone(TimeZone.getTimeZone(timeZone));
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone(timeZone));
try {
calendar.setTime(df1.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat df2 = new SimpleDateFormat("MM/dd/yyyy HH:mm a");
df2.setTimeZone(TimeZone.getDefault());
calendar.setTimeZone(TimeZone.getDefault());
return df2.format(calendar.getTime());
}
Parameter timeZone is America/New_York and expected is Asia/Calcutta
I'm getting two different string for datetime and time zone now I have to convert datetime according to device local timezone
I have used Joda-Time and with some modification I have implemented and fixed my issue.

How do I change date time format in Android?

I am displaying the date and time in Android with this format:
2013-06-18 12:41:24
How can I change it to the following format?
18-jun-2013 12:41 pm
Here is working code
public String parseDateToddMMyyyy(String time) {
String inputPattern = "yyyy-MM-dd HH:mm:ss";
String outputPattern = "dd-MMM-yyyy h:mm a";
SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
Date date = null;
String str = null;
try {
date = inputFormat.parse(time);
str = outputFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return str;
}
Documentation: SimpleDateFormat | Android Developers
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");
String date = format.format(Date.parse("Your date string"));
public class MainActivity extends AppCompatActivity {
private Date oneWayTripDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String date ="2017-05-05 13:58:50 ";
SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat output = new SimpleDateFormat("MMMM dd,yyyy #hh:mm:ss aa");
try {
oneWayTripDate = input.parse(date); // parse input
} catch (ParseException e) {
e.printStackTrace();
}
Log.e("===============","======currentData======"+output.format(oneWayTripDate);
}
}
Use this code like below:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");
String date = formatter.format(Date.parse("Your date string"));
Hope it will help you.
I modified Rusabh's answer for general purpose formatting of date in my project
public String formatDate(String dateToFormat, String inputFormat, String outputFormat) {
try {
Logger.e("DATE", "Input Date Date is " + dateToFormat);
String convertedDate = new SimpleDateFormat(outputFormat)
.format(new SimpleDateFormat(inputFormat)
.parse(dateToFormat));
Logger.e("DATE", "Output Date is " + convertedDate);
//Update Date
return convertedDate;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
Usage:
String inputFormat = "yyyy-MM-dd'T'HH:mmz";
String OutPutFormat = "MMMM dd', 'yyyy hh:mma";
String convertedDate = formatDate(asOfDateTime, inputFormat, OutPutFormat);
You have to set like this
Date date=new Date("Your date ");
SimpleDateFormat formatter5=new SimpleDateFormat("required format");
String formats1 = formatter5.format(date);
System.out.println(formats1);
set answer like this to set date format
Date date=new Date("Your date ");
SimpleDateFormat formatter5=new SimpleDateFormat("required format");
use this code below:
Date date=new Date("2013-06-18 12:41:24");
SimpleDateFormat formatter5=new SimpleDateFormat("dd-MM-yyyy hh:mm a");
String formats1 = formatter5.format(date);
System.out.println(formats1);
First Create a Calendar object using your Date object. Then build a String using date, year, month and etc you need. then you can use it.
You can get data using get() method in Calendar class.
We can use this format for convert the date. Pass the date as parameter
public String formatdate(String fdate)
{
String datetime=null;
DateFormat inputFormat = new SimpleDateFormat("dd-MM-yyyy");
SimpleDateFormat d= new SimpleDateFormat("yyyy-MM-dd");
try {
Date convertedDate = inputFormat.parse(fdate);
datetime = d.format(convertedDate);
}catch (ParseException e)
{
}
return datetime;
}
private val dateFormatter: Format = SimpleDateFormat(
android.text.format.DateFormat.getBestDateTimePattern(
Locale.getDefault(),
"dMMyyjjmmss"
),
Locale.getDefault()
)
val dateText = dateFormatter.format(Date(System.currentTimeMillis()))
This is the best choice available on Android which will format time based on device default Locate
Example output depending on Locale:
USA - 02/18/2021, 1:00:00 PM (USA uses 12 format time)
Ukraine - 18.2.2012, 13:00:00 (Ukraine uses 24 format time)
So it does all the hard job automatically for you
P.S. replace yy with yyyy if you need 2021 instead of 21, MM to MMM if you want display month as word instead of number and so on
For example "dMMMyyyyjjmmss" for USA will return:
Feb 18, 2021, 1:43:20 PM
For Russia:
18 февр. 2021 г., 13:44:18
Amazing, isn't?

String to Date Conversion Problem

I am trying to convert the following string in to date, I am able to convert the string into to date object successfully,But the Problem is in this string I want to convert the time in to am/pm i.e. 12 hr format, I tried different ways but unable to get the solution.
How to get the 12hr format time from this string ?
Here is my code:
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy"); //please notice the capital M
Date date;
try {
date = formatter.parse("Fri Jul 01 10:00:00 CDT 2011");
Log.e("ThankYou Block", ""+date.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TRY
public static String StringToDate(String dateToParse) {
Date formatter = new Date(HttpDateParser.parse(dateToParse));
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");
int offset = TimeZone.getDefault().getRawOffset();
formatter.setTime(formatter.getTime() + offset);
String strCustomDateTime = dateFormat.format(formatter);
return strCustomDateTime;
}

Categories

Resources