String to Date Conversion Problem - android

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

Related

Converting GMT to Local time format in android

I am new to android developer. I convert the GMT to local mobile time. I got am /pm issues in this code. After 6'o clock evening time . I got am in conversion.
sorry for my English. Advance thanks for help.
public String formatDate(String s)
{
String outputText=null;
try {
// Tue May 21 14:32:00 GMT 2012
String inputText =s;
SimpleDateFormat inputFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm 'GMT'", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
if(android.text.format.DateFormat.is24HourFormat(CalloutAvalibality.this))
{
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM dd,yy HH:mm");
// Adjust locale and zone appropriately
Date date = inputFormat.parse(inputText);
outputText= outputFormat.format(date)+" "+"Hrs";
System.out.println(outputText);
}
else
{
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM dd, yyyy hh:mm a");
// Adjust locale and zone appropriately
Date date = inputFormat.parse(inputText);
outputText= outputFormat.format(date);
// outputText=outputText.replace("AM","am");
// outputText=outputText.replace("PM","pm");
System.out.println(outputText);
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return outputText;
}
datefomater.format() will return you a string which is converted to timezone you initially set with the formatter object.
datefomater.parse() will return you a Date object which is in you local timezone
The Date object will set to default timezone
TimeZone timeZone = TimeZone.getTimeZone("America/Chicago");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(timeZone);
String result = formatter.format(YOUR_DATE_OBJECT);

Date format not working properly in Android

I am working on Android application in which I am saving and getting date from ORMLITE. I am using SimpleDateFormat for the formatting of the desire date, but except this pattern yyyy-MM-dd HH:mm it is not formatting it. My current date from server with desired dates with code is given below:
try {//EEEE , MMMM dd , yyyy hh:mm a
SimpleDateFormat mDBSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(cursor.getString(cursor.getColumnIndex("mLastMessageDate"))==null){//.equals("") ||cursor.getString(cursor.getColumnIndex("mLastMessageDate")).toString()==null){
mTxtLastMessageDate.setText("");
mTxtLastMessageLabel.setText("");
}else{
mTxtLastMessageDate.setText(mDBSDF.parse(cursor.getString(cursor.getColumnIndex("mLastMessageDate"))).toString());
}
}catch(Exception ex) {
ex.printStackTrace();
}
This is my server date:
2015-04-28 12:57:04.000297
After using above format i am getting this:
Tue Apr 28 12:57:04 GMT+04:00 2015
I want the pattern like this:
Tuesday, April 28, 2015 1:00 pm
Except above yyyy-MM-dd HH:mm format even if i am changing "-" to "," it is not working without any error
SimpleDateFormat.parse(String) returns a Date not a formatted String.
Use SimpleDateFormat.format(Date) instead.
Try this to format the date and time...
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
Try this base on your requirement.
Input date as string
protected String dateFormat(String sqlDate) {
String strDate = "";
java.util.Date utilDate;
SimpleDateFormat sqlDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");//input format
try {
Calendar calTempDate = Calendar.getInstance();
calTempDate.setFirstDayOfWeek(Calendar.MONDAY);
utilDate = sqlDateFormat.parse(sqlDate);
calTempDate.setTime(utilDate);
strDate = new SimpleDateFormat("EEEE MMMM dd,yyyy HH:mm a")
.format(calTempDate.getTime());//output format
} catch (Exception e) {
e.printStackTrace();
}
return strDate;
}
You can use this code to find out your solution.
SimpleDateFormat fromdateformate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date=fromdateformate.parse("2015-04-28 12:57:04.000297");
SimpleDateFormat todtaeFormate=new SimpleDateFormat("EEEE MMMM yyyy hh:mm aa");
String finaldate= todtaeFormate.format(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Change String date format and set into TextView in Android?

I want to change my date format that is in as
String date ="29/07/13";
But it is showing me the error of *Unparseable date: "29/07/2013" (at offset 2)*
I want to get date in this format 29 Jul 2013.
Here is my code that i am using to change the format.
tripDate = (TextView) findViewById(R.id.tripDate);
SimpleDateFormat df = new SimpleDateFormat("MMM d, yyyy");
try {
oneWayTripDate = df.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
tripDate.setText(oneWayTripDate.toString());
Try like this:
String date ="29/07/13";
SimpleDateFormat input = new SimpleDateFormat("dd/MM/yy");
SimpleDateFormat output = new SimpleDateFormat("dd MMM yyyy");
try {
oneWayTripDate = input.parse(date); // parse input
tripDate.setText(output.format(oneWayTripDate)); // format output
} catch (ParseException e) {
e.printStackTrace();
}
It's a 2-step process: you first need to parse the existing String into a Date object. Then you need to format the Date object into a new String.
Change the format string to MM/dd/yyyy, while parse() and use dd MMM yyyy while format().
Sample :
String str ="29/07/2013";
// parse the String "29/07/2013" to a java.util.Date object
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(str);
// format the java.util.Date object to the desired format
String formattedDate = new SimpleDateFormat("dd MMM yyyy").format(date);
DateFormat df = new SimpleDateFormat("dd / MM / yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());

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?

Android: How can I Convert String to Date?

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

Categories

Resources