How do you compare the time portion of a time string? - android

I have in my preferences some strings that represent a start time and and ending time.
I wrote this function to determine if the current time is within the start and ending time. The format of the date strings is "HH:mm". The function takes the strings that are from the preferences.
I'm sure I'm missing some code for the comparing because my parsing returns a something like this:
Thu Sep 29 12:24:33 EDT 2011
But all I need is to get this:
12:24
Here is the function. Can you help me correct the coding?
Thanks.
Truly,
Emad
public static boolean currentTimeIsWithinStartAndEnd(String startTime,
String endTime) {
String pattern = "HH:mm";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
boolean booleanValueToReturn = false;
try {
Date startTimeToCompare = sdf.parse(startTime);
Date endTimeToCompare = sdf.parse(endTime);
/*
* These are for the current time in date format.
*/
Date currentTime = new Date(System.currentTimeMillis());
Log.w("Emad", "Current Time: " + currentTime + " Start Time is: "
+ startTimeToCompare + " End Time is : "
+ endTimeToCompare);
/*
* Check if current time is equal or greater than the start time.
*/
if (currentTime.compareTo(startTimeToCompare) == 0
|| currentTime.compareTo(startTimeToCompare) == 1) {
booleanValueToReturn = true;
/*
* Now check if the current time is equal or less than the end
* time.
*/
if (currentTime.compareTo(endTimeToCompare) == 0
|| currentTime.compareTo(endTimeToCompare) == -1) {
booleanValueToReturn = true;
} else {
booleanValueToReturn = false;
}
} else {
booleanValueToReturn = false;
}
} catch (java.text.ParseException e) {
}
return booleanValueToReturn;

You are using SimpleDateFormat Incorrectly.
String pattern = "HH:mm" should be format in which your input Date String is. otherwise how is SimpleDateFormat going to know which portion represents what.
Create two SimpleDateFormat, f1 (with Input String Format) and f2 ( with output String Format) ;
Use f1.parse() to get Date object for Input String.
Then use f2.format() on this Date Object to get Output String representation.
Refer to SimpleDateFormat for details on how to specify date Format.
public static boolean currentTimeIsWithinStartAndEnd(String startTime,
String endTime) {
// assuming input date string is of format MM/dd/yyyy. Change it according to your needs.
String inputPattern = "MM/dd/yyyy";
String outputPattern = "HH:mm";
SimpleDateFormat inputFormatter = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormatter = new SimpleDateFormat(outputPattern);
Date startTimeToCompare = inputFormatter.parse(startTime);
String dateInRequiredFormat = outputFormat.format(startTimeToCompare);

Related

Time zones - how to?

The final goal is to convert a timestamp passed down from the server to local time.
Here's what I get:
2018-04-05T16:14:19.130Z
However, my local time is 11:14 AM CST. Here's what I've tried:
final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
final LocalTime localTime = formatter.parseLocalTime(text);
Timber.i(localTime.toString()); // output: 16:14:19.070
Output is: 16:14:19.070. Does anybody know how to use it? I expected to receive something like 11:14 AM.
Also, I've tried using this:
final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
final DateTime time = formatter.parseDateTime(text);
Timber.i(time.toString()); // output: 2018-04-05T16:14:19.490-05:00
Looks like it's a 5-hour difference there? Does anybody know how I can use this to convert to local time?
The "Z" in the end means that the date/time is in UTC. If you put it inside quotes, it's treated as a literal (the letter "Z" itself) and it loses this special meaning - you're basically throwing away the information that it's in UTC, and DateTime assumes the JVM default timezone (that's why your second attempt results in 16:14 in UTC-05:00).
DateTime can parse this input directly:
String input = "2018-04-05T16:14:19.130Z";
DateTime dt = DateTime.parse(input);
Then you convert this to the desired timezone. You can do:
dt = dt.withZone(DateTimeZone.getDefault());
Which will use your JVM's default timezone. But this is not so reliable, because the default can be changed at runtime - even by other applications running in the same JVM - so it's better to use an explicit timezone:
dt = dt.withZone(DateTimeZone.forID("America/Chicago"));
Then you can convert it to the format you want:
String time = dt.toString("hh:mm a"); // 11:14 AM
If you need to use a formatter, you can remove the quotes around "Z" and also set the timezone in the formatter:
DateTimeFormatter parser = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
// zone to be used for the formatter
.withZone(DateTimeZone.forID("America/Chicago"));
DateTime dateTime = parser.parseDateTime("2018-04-05T16:14:19.130Z");
String time = dateTime.toString("hh:mm a"); // 11:14 AM
Use this method to convert your time to local:
public static String convertTimeToLocal(String dateStr) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = format.parse(dateStr);
System.out.println(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String timeZone = Calendar.getInstance().getTimeZone().getID();
Date local = new Date(date.getTime() + TimeZone.getTimeZone(timeZone).getOffset(date.getTime()));
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
String reportDate = df.format(local);
return reportDate;
}
& for AM and PM, use this method:
public static String convertTimeToAmPm(String time) {
List<String> arr = Arrays.asList(time.split(":"));
int hours = Integer.parseInt(arr.get(0));
int mins = Integer.parseInt(arr.get(1));
String timeSet = "";
if (hours > 12) {
hours -= 12;
timeSet = "PM";
} else if (hours == 0) {
hours += 12;
timeSet = "AM";
} else if (hours == 12)
timeSet = "PM";
else
timeSet = "AM";
String minutes = "";
if (mins < 10)
minutes = "0" + mins;
else
minutes = String.valueOf(mins);
// Append in a StringBuilder
String aTime = new StringBuilder().append(hours).append(':')
.append(minutes).append(" ").append(timeSet).toString();
return aTime;
}

How to convert number to hour and minute in android

In my application i should show hour and minute and i get this numbers from server with this sample :
Json :
{
data:{
time:84561
}
}
i should get this number from time and show it with this format
**hh : mm : ss**
I can get number of time, but i can't convert this to **hh : mm : ss** .
How can i it?
long timeSec= 84561;// Json output
int hours = (int) timeSec/ 3600;
int temp = (int) timeSec- hours * 3600;
int mins = temp / 60;
temp = temp - mins * 60;
int secs = temp;
String requiredFormat = hours+ ": "+mins+": "+secs;//hh:mm:ss formatted string
Java 9 answer
Duration time = Duration.ofSeconds(87561);
String hms = String.format("%02d : %02d : %02d",
time.toHoursPart(),
time.toMinutesPart(),
time.toSecondsPart());
Unfortunately in Java 8 Duration does not lend itself well to formatting. The methods I use in the snippet are introduced in Java 9 and will calculate the values for hh, mm and ss. Then String.format() does the rest.
I know you cannot use this on Andriod (yet), but I wanted to have this answer stand here for others who can use Java 9, now or in the future.
Very simple
If this is unix time then it will be converted into human readable time format with this snippet.
String relavtiveTimeString = String.valueOf(DateUtils.getRelativeTimeSpanString(unixTime));
You can use new Date(unix); and with below function you can get formatted date. You can format in different style.
//This mehtod convert the date into standard date like : 2017-12-23
public static String getformateDate(Date dateObject) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.format(dateObject);
}
For more information check this link already answer :
Convert unix time stamp to date in java
Referance:
https://developer.android.com/reference/android/text/format/DateUtils.html
https://developer.android.com/reference/android/text/format/Time.html
Pass your Number or timestamp and convert to milliseconds for hour and minute.use the below code.
public static String getCurrentTimeStamp(String mCurrentTime) {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm a z");
TimeZone tz = TimeZone.getDefault();
format.setTimeZone(tz);
// System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
SimpleDateFormat dateParser = new SimpleDateFormat("dd/MM/yyyy hh:mm a z");
Date dateTime = null;
try {
dateTime = dateParser.parse(format.format(Long.parseLong((mCurrentTime)) * 1000));
Log.e("Starttime", "Starttime" + format.format(dateTime));
return format.format(dateTime);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
Try This Logic Use it As per Requirement
public class Test {
public static void main(String[] args) {
String json = "{\n" +
" data:{\n" +
" time:84561\n" +
" }\n" +
"}";
Date date = new Gson().fromJson(json, Date.class);
long milli = date.getTime() * 1000;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println(simpleDateFormat.format(new java.util.Date(milli)));
}
class Date implements Serializable{
int time;
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
}
Output
05:30:00
If you want to download Gson jar download it from
here

Format date to local setting but only for month and day

My date is in a string in the format "2013-12-31". I want to convert this to a local date based upon the user's device setting but only show the month and day. So if the user's device is set to German, the date should be converted to "31.12". In Germany, the day comes first followed by the month. I don't want the year to be included.
For Build.VERSION.SDK_INT < 18 I could not find a way to obtain a month/day format that obeys user preferences. This answer works if you are willing to accept month/day in user's locale default pattern (not their preferred order or format). My implementation uses the full numeric format in versions less than 18 or if any issues are encountered in the following carefully programmed series of steps.
Get user's numeric date format pattern as String
Reduce pattern to skeleton format without symbols or years
Obtain localized month/day format with DateFormat.getBestDateTimePattern
Reorder localized month/day format according to user preferred order. (key assumption: days and months can be naively swapped for all localized numeric formats)
This should result in a month/day pattern that obeys user's preference in localized formatting.
Get user date pattern string per this answer:
java.text.DateFormat shortDateFormat = DateFormat.getDateFormat(context);
if (shortDateFormat instanceof SimpleDateFormat) {
String textPattern = ((SimpleDateFormat) shortDateFormat).toPattern();
}
Reduce pattern to day/month skeleton by removing all characters not 'd' or 'M', example result:
String skeletonPattern = 'ddMM'
Get localized month/day format:
String workingFormat = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeletonPattern);
(note: this method requires api 18 and above and does not return values in user-preferred order or format, hence this long-winded answer):
Get user preferred date order ('M', 'd', 'y') from this method:
char[] order = DateFormat.getDateFormatOrder(context);
(note: I suppose you could parse the original pattern to get this information too)
If workingFormat is in the correct order, your job is finished. Otherwise, switch the 'd's and the 'M's in the pattern.
The key assumption here is that days and months can be naively swapped for all localized numeric formats.
DateFormat monthDayFormat = new SimpleDateFormat(workingFormat);
I think, this is the simplest solution for apps targeting API > 17:
dateFormat = SimpleDateFormat(DateFormat.getBestDateTimePattern(Locale.getDefault(), "MMMM dd"), Locale.getDefault())
A bit late, bit I also faced the same issue. That is how I solved it:
String dayMonthDateString = getDayMonthDateString("2010-12-31", "yyyy-MM-dd", Locale.GERMANY);
Log.i("customDate", "dayMonthDateString = " + dayMonthDateString);
private String getDayMonthDateString(String dateString, String dateFormatString, Locale locale)
{
try
{
boolean dayBeforeMonth = defineDayMonthOrder(locale);
String calendarDate = dateString;
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString);
Date date = dateFormat.parse(calendarDate);
SimpleDateFormat newDateFormat;
if (dayBeforeMonth)
{
newDateFormat = new SimpleDateFormat("dd.MM", locale);
}
else
{
newDateFormat = new SimpleDateFormat("MM.dd", locale);
}
return newDateFormat.format(date);
}
catch (ParseException e)
{
e.printStackTrace();
}
return null;
}
private boolean defineDayMonthOrder(Locale locale) throws ParseException
{
String day = "10";
String month = "11";
String year = "12";
String calendarDate = day + "." + month + "." + year;
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yy");
Date date = format.parse(calendarDate);
String localizedDate = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, locale).format(date);
int indexOfDay = localizedDate.indexOf(day);
int indexOfMonth = localizedDate.indexOf(month);
return indexOfDay < indexOfMonth ? true : false;
}
Let me know of any questions you could have related to the solution.
Keep it simple, we already have a method for this (API 18+):
String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), "yyyy-MM-dd");
SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.getDefault());
String output = format.format(currentTimeMs);
Today its 2019 July 18:
In Europe, the output will be
18.07.2019
In the US, the output will be:
07/18/2019
This works:
String dtStart = "2010-12-31";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(dtStart);
SimpleDateFormat df = (SimpleDateFormat)
DateFormat.getDateInstance(DateFormat.SHORT);
String pattern = df.toLocalizedPattern().replaceAll(".?[Yy].?", "");
System.out.println(pattern);
SimpleDateFormat mdf = new SimpleDateFormat(pattern);
String localDate = mdf.format(date);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd.MM");
try {
Date date = inputFormat.parse("2013-12-31");
String out = outputFormat.format(date);
// out is 31.12
} catch (ParseException e) {
e.printStackTrace();
}

How can i convert dropbox log timestamp?

I am debugging a android framework.
I pull out dropbox logs from device and it's created in /data/system/dropbox.
Log file name is printed like this format.
event_data#1362451303699
1362451303699 is timestamp and i want to change it like 05/03/2013 16:00 for legibility.
How can i convert this timestamp?
Is there any code needs to be changed?
Any help will be much appreciated.
use: Date date = new Date(timestamp);
Edit full code:
String wantedDate = "";
String log = "event_data#1362451303699";
int index = log.indexOf("#");
if(index != -1) {
index = index + 1; // skip # symbol
if(index < log.length()) { // avoid out of bounds
String logtime = log.substring(+1);
try {
long timestamp = Long.parseLong(logtime);
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = new Date(timestamp);
wantedDate = df.format(date);
} catch (NumberFormatException nfe) {
// not a number
}
}
}
if( ! "".equals(wantedDate) ) {
// everything OK
} else {
// error cannot retrieve date!
}
Related doc:
indexOf : http://developer.android.com/reference/java/lang/String.html#indexOf%28java.lang.String%29
SimpleDateFormat : http://developer.android.com/reference/java/text/SimpleDateFormat.html
you can use a SimepleDateFormat to parse it. For example:
long ts = 1362451303699;
Date date = new Date(ts);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
System.out.println(sdf.format(date));
With the SimpleDateFormat you can bring your Date in a more readable format.
It is a UNIX epoch timestamp, all you need to do is to convert the String representation of the number to long, then you can use it to create a Date object, which you can format with DateFormat. Something like this:
// Get this from the log
String timestamp = "1362451303699";
long epoch = Long.parseLong(timestamp);
Date date = new Date(epoch);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String formattedDate = format.format(date);

Date format to match the Date format in Phone Settings

I have a string which returns the date and time as 2012-11-08 12:45:30 . I need to get the date and time in separate strings and then the date has to be shown in the format which is there in the Phone's Date and Time settings.
Here is the code which I have tried so far:
date value from db is 2012-11-08
I am getting the date format in phone's settings as
String datefrmt = Settings.System.getString(
context.getContentResolver(), Settings.System.DATE_FORMAT);
the code to apply this format to the obtained date from db is:
SimpleDateFormat sdf = new SimpleDateFormat(datefrmt);
java.util.Date date_1 = sdf.parse("2012-11-08");
String s = sdf.format(date_1);
I am getting the month and day properly but the year its returning something randomly and thats not a correct value. Can anyone please guide me where am I going wrong. Thanks
If you have 2012-11-08 12:45:30 string and you want to parse it to Date object and change its format to another (system format for example or 2012-11-08 format):
try {
String yourString="2012-11-08 12:45:30";
//first we parse input date string and create Date object
String inputDateString ="yyyy-dd-MM hh:mm:ss";
SimpleDateFormat inputDateFormat = new SimpleDateFormat(inputDateString);
java.util.Date date = inputDateFormat.parse(yourString);
//log
Log.e(getClass().getName(), inputDateFormat.format(date));
//create system date format
String dateformt = Settings.System.getString( this.getContentResolver(), Settings.System.DATE_FORMAT);
//if its for some reason==null let it be "yyyy-dd-MM"
if(dateformt==null){
dateformt="yyyy-dd-MM";
}
SimpleDateFormat systemDateFormat = new SimpleDateFormat(dateformt);
String outputString = systemDateFormat.format(date);
//log
Log.e(getClass().getName(), outputString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
you can use the simpleDateFormat as:
SimpleDateFormat simpDate = new SimpleDateFormat(datefrmt,
Locale.ENGLISH);
String s = simpDate.format(new Date());
for reference, you can refer to developer site:
for more information refer this link
Since your DB date is in yyyy-MM-dd, don't use the dynamic format to get the date, otherwise it will crash(throw parse exception), instead use the static format as below to get the date. You may use the dynamic format to convert the string as below:
//use static format to convert into date from static formatted data in db
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date_1 = sdf1.parse("2012-11-08");//got the date
//use the dynamic format to convert into string
SimpleDateFormat sdf2 = new SimpleDateFormat(datefrmt);
String s = sdf2.format(date_1);
Since final String format = Settings.System.getString(getActivity().getContentResolver(), Settings.System.DATE_FORMAT);//may be NULL
So I customized my function as below for general purposes
#SuppressLint("SimpleDateFormat")
public String getCurrentShortDateFormat() {
final String[] SFs = new String [] {
"MM/dd/yyyy",
"dd/MM/yyyy",
"yyyy/MM/dd"
};
final Date date = new Date(24638400000L);//24638400000=Oct/13/1970; 0==Jan/1/1970
java.text.DateFormat shortDateFormat = android.text.format.DateFormat.getDateFormat(getActivity().getApplicationContext());
String current = shortDateFormat.format(date);
SimpleDateFormat which = new SimpleDateFormat();
for (int i = 0; i < SFs.length; i++) {
which.applyPattern(SFs[i]);
if (which.format(date).compareTo(current)==0)
return SFs[i];
}
return null;
}
#Override
public void onResume() {
super.onResume();
Log.d(LOG_TAG, "----- onResume.CurrentShortDateFormat-----" + getCurrentShortDateFormat());
}

Categories

Resources