Hi all I am using below code to get android phone time, but it is giving me minutes without zero if the minutes are in between 1 to 9.
for example:right now I have time on my device 12:09 but its giving me as 12:9
Calendar c = Calendar.getInstance();
int hrs = c.get(Calendar.HOUR);
int mnts = c.get(Calendar.MINUTE);
String curTime = "" + hrs + ":" + mnts;
return curTime;
after above code I also try below code its giving same thing as above, minutes without zero before number it the minutes in between 1 to 9 . .
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
Date date = cal.getTime();
int mHour = date.getHours();
int mMinute = date.getMinutes();
As Egor said, an int is just an integer. Integers don't have leading zeros. They can only be displayed with leading zeros when you convert them to String objects. One way to do that is like this:
String curTime = String.format("%02d:%02d", hrs, mnts);
The format string %02d formats an integer with leading zeros (that's the 0 in %02d), always taking up 2 digits of width (that's the 2 in %02d).
That would produce the String
12:09
All is said about integer. But dealing with dates and Calendars to display that information should be used like so:
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yourpattern"); //like "HH:mm" or just "mm", whatever you want
String stringRepresentation = sdf.format(date);
the pattern "mm" will have a leading zero if it is between 0 and 9. If you use "mmmm" you'll get 0009, which doesn't look like it makes a lot of sense, but it all depends on what you want. :)
if you use pattern HH:mm you'll get 12:09 (the current time of your date instance).
You can format date using SimpleDateFormat class
if you are getting date and time from Calendar instance:-
final Calendar c = Calendar.getInstance();
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
timeEdittext.setText(timeFormat.format(c.getTime()));
dateEdittext.setText(dateFormat.format(c.getTime()));
if you have day, month, year, hour, minute as integer(usually happens in datepicker and timepicker dialogs)
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, dayOfMonth);
String date = new SimpleDateFormat("dd-MM-yyyy").format(calendar.getTime());
Used below method to convert Hour:Minute in double format.
/*
* make double format hour:minute string
* #hour : 1
* #minute : 2
* return : 01:02
* */
public static String hourMinuteZero(int hour,int mnts){
String hourZero = (hour >=10)? Integer.toString(hour):String.format("0%s",Integer.toString(hour));
String minuteZero = (mnts >=10)? Integer.toString(mnts):String.format("0%s",Integer.toString(mnts));
return hourZero+":"+minuteZero;
}
function time()
{
var time = new Date();
var hh = time.getHours();
var mmm = time.getMinutes();
if(mmm<10)
{
mmm='0'+mmm
}
time = 'T'+hh+':'+mmm;
return time;
}
Related
I am working on codename one project and I am struggling to convert device time to UTC.
I use this code :
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTimeZone());
TimeZone tzUTC = TimeZone.getTimeZone("UTC");
com.codename1.l10n.DateFormat dtfmt = new com.codename1.l10n.SimpleDateFormat("EEE, yyyy-MM-dd KK:mm a z");
dtfmt.setTimeZone(tzUTC);
System.out.println("UTC: " + dtfmt.format(cal.getTime()));
and codename one reject the setTImeZone method.
I use java.text.DateFormat but when I run it, condename one cant compile it also.
It may not really answer your real question, but the following works for me:
Calendar cal = Calendar.getInstance();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
TimeZone tzUtc = TimeZone.getTimeZone("UTC");
df.setTimeZone(tzUtc);
System.out.println("UTC: " + df.format(cal.getTime()));
I don’t know com.codename1.l10n.DateFormat, so I’m sorry I cannot help you there.
Use:
java.util.Calendar cal = java.util.Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
cal.setTime(new Date(System.currentTimeMillis() - tz.getRawOffset()));
com.codename1.l10n.DateFormat dtfmt = new com.codename1.l10n.SimpleDateFormat("EEE, yyyy-MM-dd KK:mm a");
System.out.println("UTC: " + dtfmt.format(cal.getTime()));
Then append UTC to the string as the value is always UTC.
Was using Shai's solution but noticed that it wasn't giving the correct UTC time when the device timezone was in daylight savings time. Below is a more general solution using tz.getOffset() instead of tz.getRawOffset(). Seems like there should be simpler way!
L10NManager l10n = L10NManager.getInstance();
long sysRtnTime = System.currentTimeMillis() / 1000L;
Date errorDate = new Date(sysRtnTime * 1000L);
Date currentDate = new Date();
String deviceTime = l10n.formatDateTime(errorDate);
Calendar c = Calendar.getInstance();
long unixtime = errorDate.getTime();
TimeZone tz = c.getTimeZone();
// to get offset, we need era, year, month, day, dayOfWeek,millis
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
SimpleDateFormat monthDateFormat = new SimpleDateFormat("MM");
SimpleDateFormat dayDateFormat = new SimpleDateFormat("dd");
SimpleDateFormat dayOfWeekDateFormat = new SimpleDateFormat("F");
SimpleDateFormat millisDateFormat = new SimpleDateFormat("S");
int year = Integer.parseInt(yearFormat.format(currentDate));
int month = Integer.parseInt(monthDateFormat.format(currentDate));
int day = Integer.parseInt(dayDateFormat.format(currentDate));
int dayOfWeek = Integer.parseInt(dayOfWeekDateFormat.format(currentDate));
int millis = Integer.parseInt(millisDateFormat.format(currentDate));
// c.setTime(new Date(unixtime - tz.getRawOffset())); // c in UTC only if device not DST
month = month - 1; // since getOffset assume 0 = Jan and 11 = Dec
c.setTime(new Date(unixtime - tz.getOffset(1, year, month, day, dayOfWeek, millis))); // c in UTC (even if device in DST)
Date cDateUTC = c.getTime(); // sDate in UTC
String timeInUTC = serverDateFormat.format(cDateUTC);
Log.p("Time (in device timezone): " + deviceTime);
Log.p("Time (in UTC): " + timeInUTC);
This question already has answers here:
How to determine day of week by passing specific date?
(28 answers)
Closed 7 years ago.
I have this string
String s = "29/04/2015"
And I want it to produce the name of that day in my language, which is Norwegian.
For example:
29/04/2015 is "Onsdag"
30/04/2015 is "Torsdag"
How can I do this?
String dateString = "29/04/2015";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = dateFormat.parse(dateString);
SimpleDateFormat formatter = new SimpleDateFormat("E", Locale.no_NO);
String day = formatter.format(date);
Now day will have the day in given locale. Update
You need to configure an instance of DateFormat, with your locale, (take a look at https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html).
then parse the Date and get the day, as Dilip already suggests.
You can use date parsing combined with Locale settings to get the desired output. For e.g. refer following code.
String dateStr = "29/04/2015";
SimpleDateFormat dtf = new SimpleDateFormat("dd/MM/yyyy");
Date dt = dtf.parse(dateStr);
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
String m = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG_FORMAT, new Locale("no", "NO"));
System.out.println(m);
For more information about locale, visit Oracle Java Documentation.
First you will need to parse the String to a Date. Then use a Calendar to get the day of the week. You can use an array to convert it to the appropriate string.
// Array of Days
final String[] DAYS = {
"søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"
};
// Parse the date
final String source = "27/04/2015";
final DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
try {
date = format.parse(source);
} catch (final ParseException e) {
e.printStackTrace();
}
// Convert to calendar
final Calendar c = Calendar.getInstance();
c.setTime(date);
final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
// Get the day's name
System.out.println("Day of Week: " + dayOfWeek);
System.out.println("Day = " + DAYS[dayOfWeek - 1]);
You need to parse your text with date to Date instance and then format it back to text. You can do it with SimpleDateFormat class which supports many patterns of dates like
dd/MM/yyyy for your original date,
and EEEE for full name of day in month.
While formatting you will also need to specify locale you want to use. To create Norway specific locale you can use for instance
Locale nor = Locale.forLanguageTag("no-NO");
So your code can look more or less like:
String text = "29/04/2015";
Locale nor = Locale.forLanguageTag("no-NO");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", nor);
SimpleDateFormat dayOfWeek = new SimpleDateFormat("EEEE", nor);
Date date = sdf.parse(text);
System.out.println(dayOfWeek.format(date));
Output: onsdag.
final int SUNDAY = 1;
final int ONSDAG = 2;
final int TORSDAG = 3;
....
....
String s = "29/04/2015";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = dateFormat.parse(s);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int day = calendar.get(Calendar.DAY_OF_WEEK);
String dayString;
switch (day) {
case(ONSDAG):
dayString = "ONSDAG";
break;
....
}
EDIT: I just tested this and it actually starts from Sunday, and returns the value of 1 for sunday, I've changed the constant values to reflect this.
First you'll need a Calendar object.
Calendar cal = Calendar.getInstance();
String s = "29/04/2015"
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
cal.setTime(format.parse(s));
From the Calendar you can get the day of the week.
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
dayOfWeek will be 1-7 with Sunday (in english) being 1
You can use an HashMap map where the first parametri is the date "29/4/2015" while the second is the meaning. You can use your string to get the meaning map.get (yourString).
I have a date stored in a String field in SQLITE with the String value
"/Date(1411472160000+0100)/"
how can I convert this back into a date format , the code below doesn't work. I think I need to convert from the milliseconds first but I cant see how to even get the above text into a long format first ?
any suggestions ?
Date convertedDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm",
java.util.Locale.getDefault());
convertedDate = dateFormat.parse(dateString);
return dateFormat.format(convertedDate);
Well, a substring from the indexOf("(") to the indexOf("+") and you should find the date in milli.
From there, I believe you can find the date ;)
String s = "/Date(1411472160000+0100)/";
s = s.substring(s.indexOf("(") + 1, s.indexOf("+"));
Date d = new Date(Long.parseLong(s));
With the same structure, you can find the timezone (+0100) (from "+" to ")") and work with a Calendar to find the right time for the right time area.
First you have to parse out the time value from String i.e. "1411472160000+0100" part.
Here in "1411472160000+0100" , "+0100" is the timezone info. If you don't want to consider the timezone, then you can take following approach.
Approach-1
long timestamp = 1245613885;
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(timestamp * 1000);
int year = calendar.get(Calendar.YEAR);
int day = calendar.get(Calendar.DATE);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
then to get the date in your specified format you can use-
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(calendar.getTime());
System.out.println(dateString); // 2009-06-21 15:51:25
Besides this approach, there is an excellent Java Date library called JodaTime.
If you want to incorporate the timezone info , you can refer to this constructor from JodaTime.
http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#DateTime-long-org.joda.time.DateTimeZone-
This question already has answers here:
Change date format in a Java string
(22 answers)
Closed 8 years ago.
I have a object that giving date and time in this format "2014-06-11 16:32:36.828".
I want to remove millisec .828.
In my db that object is in time stamp format but whenever i am showing i am converting it to tostring().
so how to remove millisec please help me
The following code convert "2014-06-11 16:32:36.828" into "2014-06-11 16:32:36"
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2014-06-11 16:32:36.828"));
Explanation:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2014-06-11 16:32:36.828") parse the input string into
Wed Jun 11 16:32:36 IST 2014
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) format the input date into specified structure.
I would use DateUtils.truncate(date, Calendar.SECOND)
Date d = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(yourString);
Calendar c = Calendar.getInstance();
c.setTime(d);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
I remember there is a way to directly read Date off your timestamp field but I don't do that in my everyday coding. So I'd left for others to post so. Nevertheless, you can use the same above code to translate your date from that timestamp into a date without MILLISECOND.
If you receive it as a Timestamp, you should use the appropriate formatter when converting it to a string:
String s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
Note: this will use the default time zone of the local computer.
Extract epoch millis from the original Date object and do integer division by 1000 followed by multiplication by 1000. Create Date object with the time zone of the original object and the millis calculated the above suggested way.
You can get the system time as follows without milliseconds
import java.text.SimpleDateFormat;
import java.util.Calendar;
And the code
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter= new SimpleDateFormat("dd-MM-YYYY-hh:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
System.out.println(dateNow);
if you want to mantain the format try something like that:
public static String getFechaTimestampToString (Timestamp timestamp) {
String date = "";
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(timestamp.getTime()));
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+1;
int day = cal.get(Calendar.DAY_OF_MONTH);
String monthstr = "";
String daystr = "";
if(month<10)
monthstr = "0"+month;
else
monthstr = ""+month;
if(day<10)
daystr = "0"+day;
else
daystr = ""+day;
date = year + "-" + monthstr + "-" + daystr ;
return date;
}
To reverse data to database:
public static Timestamp getFechaStringToTimestamp (String strDate) {
Timestamp timestamp = null;
strDate = strDate + " 00:00:00";
timestamp = Timestamp.valueOf(strDate);
return timestamp;
}
I'm a beginner in java/android but I am trying to make an app. A user must type in a time like 13:45 and then the app should substrat ex. 00:30 minutes from that time. That gives the result 13:15.
I have tried many different things but it wont work.
I have somthing like this. (At this stage I've hardcoded two times)
String time1 = "00:30";
String time2 = "13:45";
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long result= date2.getTime() - date1.getTime();
String strLong = Long.toString(result);
textView4.setText(strLong);
I'm getting an error in the format.parse(time1) and format.parse(time2). Is this the right way to do this? Any help? Thanks
Use Calendar type.
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date2 = format.parse(time2);
Calendar cal=Calendar.getInstance();
cal.setTime(date2);
cal.add(Calendar.MINUTE, -30); //Subtract 30 Min
String strLong= format.format(cal.getTime());
textView4.setText(strLong);