How to convert Date format to SimpleDateFormat on android? - android

recently I get String "23:00" .
I know convert string to Date
private String strtime;
private Date datetime;
SimpleDateFormat simtime = new SimpleDateFormat("HH:mm");
datatime = simtime.parse(strtime);
datetime is --> `Thu Jan 01 23:00:00 GMT+09:00 1970
but I want only get 23:00
how to use convert date to simpledateformat?

My answer below may not help people but can help #hyunwookcho somehow.
I think you want to compare that HH:mm to current time. So I recommend you to change to other way: Compare that String with current HH:mm.
private String strtime = "23:00";
private String currentHours = "";
SimpleDateFormat simtime = new SimpleDateFormat("HH:mm");
currentHours = simtime.format(Calendar.getInstance().getTime());
if (strtime.equals(currentHours)){
//same hours
}else{
//diff hours
}
UPDATE
If you want to compare between 2 points of time. I suggest you use this
String strtime1 = "23:00";
String strtime2 = "17:00";
String currentHours = "";
String[] strs_time1 = strtime1.split(":");
String[] strs_time2 = strtime2.split(":");
Calendar c_time1 = Calendar.getInstance();
c_time1.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strs_time1[0]));
c_time1.set(Calendar.MINUTE, Integer.parseInt(strs_time1[1]));
Calendar c_time2 = Calendar.getInstance();
c_time2.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strs_time2[0]));
c_time2.set(Calendar.MINUTE, Integer.parseInt(strs_time2[1]));
Calendar currentCal = Calendar.getInstance();
if (currentCal.getTimeInMillis() >= c_time2.getTimeInMillis() && currentCal.getTimeInMillis() <= c_time1.getTimeInMillis()){
// FIRE IN THE HOLE
}

public static final String TimeFormate = "hh:mm a";
public static String getCurrentDateTime() {
SimpleDateFormat from = new SimpleDateFormat(TimeFormate);
from.setTimeZone(TimeZone.getDefault());
String current = from.format(new Date());
return current;
}
it will help you for sure, It will provide you your perspective time format

Related

How to change String that contains month and year only using simpledateformat

im having trouble with SimpleDateFormat. as I'm new to Android Studio Java
I have this string
which is String monthYear = "05/2019".
I want to change it to String monthYear = "May 2019".
may i know how to achieve this by having the result back as string ?
Here's what you can do:
// from string to date
String monthYear = "05/2019";
SimpleDateFormat inputFormat = new SimpleDateFormat("MM/yyyy");
Date date = inputFormat.parse(monthYear);
// from date to string
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM yyyy");
String dateTime = outputFormat.format(date);

how can i get the date full time of specific string format

I have an API contains string date with this format "/Date(1527677209864)/", how can I get the date and time to be used in Android app
You can use Date with the epoch number as a parameter in the constructor.
First you have to strip /Date( and )/ from the string, this you can do with regex.
Pattern pattern = Pattern.compile("\\D+([0-9]+)\\D+");
Matcher matcher = pattern.matcher("/Date(1527677209864)/");
if (matcher.matches()) {
long timestamp = Long.parseLong(matcher.group(1));
Date actualDate = new Date(timestamp);
}
I'm assuming that 1527677209864 value is a timestamp, right?
Try this function:
public static String getDateAndTime(#NotNull Context context, long timestamp) {
Date date = new Date(timestamp * 1000);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
DateFormat df = new SimpleDateFormat(getTimeFormat(context), Locale.getDefault());
return df.format(date);
}
Let me know if this is what you were looking for.
Remove the prefix /Date( and suffix )/. Use the result to initialize a java.util.Date.
String dt = "/Date(1527677209864)/";
dt = dt.substring(6, dt.indexOf(")/"));
long timestamp = Long.parseLong(dt);
Date date = new Date(timestamp);
Use SimpleDateFormat to format this date to your required format.
We have to filter the timeInMillis value from the string and convert it to long so that we can use or set it in calendar and get the date object.
Date convertToDate(String input) {
// input = "/Date(1527677209864)/";
String timeString = input.substring(6, input.length() - 2);
Long time = Long.parseLong(timeString);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
return calendar.getTime();
}
Then we can format the date object to string according to our desire patter or format.
String convertDateToString(Date date, String pattern) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
return formatter.format(date);
}
Try this
String jsonDate = "/Date(1527677209864)/";
jsonDate = jsonDate.substring(6, 13);
int unix_timestamp = Integer.parseInt(jsonDate);
Date date = new Date(unix_timestamp);

how to get the current date of android phone?

This is how i get the phone's date, but it prompts me with a parseException, what's the problem?
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(new Date());
Date localDate = sdf.parse(date);
new Date(0) is not the current date/time. You should use new Date(). ParseException should go away then. If you wanna know why you got that, simply debug your program and have a look at what new Date(0) gives as a String, you'll know why it fails to be parsed.
Date now = new Date();
Date alsoNow = Calendar.getInstance().getTime();
String nowAsString = new SimpleDateFormat("yyyy-MM-dd").format(now);
That works. And that too:
Date christmas = new SimpleDateFormat("yyyy-MM-dd").parse("2012-12-25");
By the way, make sure you are using java.util.Date and not java.sql.Date
Calendar now = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String nowDate = formatter.format(now.getTime());
String[] separateCurrentDate = nowDate.split("-");
String year = separateCurrentDate[0];
String month = separateCurrentDate[1];
String day = separateCurrentDate[2];
int currentYear = Integer.parseInt(year);
int currentMonth = Integer.parseInt(month);
int currentDay = Integer.parseInt(day);
and then store y,m,d one by one into a Date type onject
Date now = new Date();
Date alsoNow = Calendar.getInstance().getTime();
String nowAsString = new SimpleDateFormat("yyyy-MM-dd").format(now);
currentdate = (TextView)findViewById(R.id.textcntdate);
currentdate.setText(nowAsString);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
And then also here is another link on this
Display the current time and date in an Android application

Get preferred date format string of Android system

Does anybody know how to get the format string used by the system when formatting a date using
DateFormat.getLongDateFormat(Context context).format(Date date)
To get the date format pattern you can do:
Format dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
String pattern = ((SimpleDateFormat) dateFormat).toLocalizedPattern();
I wrote a method to detect this format string. ( work for my case).
public static String getDateFormat(Context context){
// 25/12/2013
Calendar testDate = Calendar.getInstance();
testDate.set(Calendar.YEAR, 2013);
testDate.set(Calendar.MONTH, Calendar.DECEMBER);
testDate.set(Calendar.DAY_OF_MONTH, 25);
Format format = android.text.format.DateFormat.getDateFormat(context);
String testDateFormat = format.format(testDate.getTime());
String[] parts = testDateFormat.split("/");
StringBuilder sb = new StringBuilder();
for(String s : parts){
if(s.equals("25")){
sb.append("dd/");
}
if(s.equals("12")){
sb.append("MM/");
}
if(s.equals("2013")){
sb.append("yyyy/");
}
}
return sb.toString().substring(0, sb.toString().length()-1);
}
EDIT Please check the Mark Melling's answer below https://stackoverflow.com/a/18982842/945808 to have better solution. Mine was just a hack long time ago.
There is a static method in the API that you can call like this:
Format dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
There is more discussion about it here.
You can use this:
private static DateFormat mDateFormat;
private static DateFormat mTimeFormat;
mDateFormat = android.text.format.DateFormat.getDateFormat(this);
mTimeFormat = android.text.format.DateFormat.getTimeFormat(this);
public static String getSystemDateFormat() {
return ((SimpleDateFormat) mDateFormat).toPattern();
}
public static String getSystemTimeFormat() {
return ((SimpleDateFormat) mTimeFormat).toPattern();
}
public static String getSystemDateTimeFormat() {
return getSystemDateFormat() + " " + getSystemTimeFormat();
}
based on an answer above:
String pattern = Settings.System.getString(getActivity().getContentResolver(),
Settings.System.DATE_FORMAT);
String format;
if (pattern.indexOf("d")<pattern.indexOf("M"))
format = "d/M";
else
format = "M/d";
SimpleDateFormat df = new SimpleDateFormat(format);
and then use the SimpleDateFormat to format your Date objects. It's working for me.
SimpleDateFormat
I use SimpleDateFormat without custom pattern to get actual date and time in preferred format from system:
public static String getFormattedDate() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat(); //called without pattern
return df.format(c.getTime());
}
returns:
13.01.15 11:45
1/13/15 10:45 AM
...
According to the DateFormat documentation:
To format a date for the current Locale, use one of the static factory
methods:
myString = DateFormat.getDateInstance().format(myDate);
And to format it for a different locale:
myString = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE).format(myDate);
String shortDateFormat = Settings.System.getString(context.getContentResolver(), Settings.System.DATE_FORMAT);

How can i get the time of a TimePicker in this format -> "08:00:00"?

i have a android timepicker, and i need to get his time in java code, and transform it into a string with this appereance: "08:00:00" (hours, mins, secs)
can someone help me to do it in a easy way?
code example will be appreciated
TimePicker t = new TimePicker(this);
String formattedTime = "";
int hour = t.getCurrentHour();
String sHour = "00";
if(hour < 10){
sHour = "0"+hour;
} else {
sHour = String.valueOf(hour);
}
int minute = t.getCurrentMinute();
String sMinute = "00";
if(minute < 10){
sMinute = "0"+minute;
} else {
sMinute = String.valueOf(minute);
}
formattedTime = sHour+":"+sMinute+":"+"00"; // Sorry you can't get seconds from a TimePicker
TimePicker has 2 methods available to get the set time. getCurrentHour and getCurrentMinute.
So outputting this as a string shouldn't be too hard.
String s;
Format formatter;
Calendar calendar = Calendar.getInstance();
// tp = TimePicker
calendar.set(Calendar.HOUR_OF_DAY, tp.getCurrentHour());
calendar.set(Calendar.MINUTE, tp.setCurrentMinutes());
calendar.clear(Calendar.SECOND); //reset seconds to zero
formatter = new SimpleDateFormat("HH:mm:ss");
s = formatter.format(calendar.getTime()); // 08:00:00
By the way, lowercase hh will get you a 12 hour clock.
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String formatted = format.format(date); // date is a long in milliseconds
Just use SimpleDateFormat to format date and time .
Calendar cal=new Calendar();
SimpleDateFormat frmDate=SimpleDateFormat("dd-MM-yyyy");
String s=frmDate.format(cal.getTime());
SimpleDateFormat frmTime=SimpleDateFormat("HH:MM:SS");
String t=frmTime.formate(cal.getTime());
http://developer.android.com/reference/java/text/SimpleDateFormat.html
http://developer.android.com/reference/java/text/DateFormat.html
Also check out DateUtils, very useful.
Please find the below code:
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String formatted = format.format(date); // date is a long in milliseconds

Categories

Resources