I'm trying to get a time string in the format of YYYYMMDD-HHMMSSMilliseconds in Android
Ex: 20130312-1723437520 (2013 March 12th, 17 Hour 23 Minutes 43 Seconds 7520 Milliseconds)
Time now = new Time();
now.setToNow();
String snapshotTime = now.format("yyyyMMdd-HHmmss");
First of all, above code doesn't even work properly. snapshotTime is always set to the format string itself.
Second of all, according to the Android documentation, there's no way to record milliseconds.
How can I accomplish this?
See the SimpleDateFormat class, you can format a Date object into the required format (upper-case S will give millis)
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String str = fmt.format(now);
That said, using Joda Time is usually a good idea (Proguard will strip code you don't use).
You'll have to use the strftime formatting, as noted in the Android docs.
Time now = new Time();
now.setToNow();
String snapshotTime = now.format("%Y%m%d-%H%M%S");
If you really want to use milliseconds than I would recommend SimpleDateFormat.
Try getting the time as unix timestamp with milliseconds from
long currentTime = System.currentTimeMillis();
or convert your time to milliseconds:
long currentTime = now.toMillis(true);
Then you can convert this to your desired date:
Time now = new Time();
now.set(currentTime);
String snapshotTime = now.format("%Y%m%d-%H%M%S")+""+(currentTime%1000);
Didn't test it but hope it works :)
I would recommend to use this little library, it's very helpful when working with dates. Have a look at the DateTimeFormatter class.
As an alternative use Calendar and SimpleDateFormater (you'll have to adjust the format string of course, see this for explanation of the symbols)
Calendar c = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-SSSS");
String date = sdf.format(c.getTime());
You can try this:
public static String format() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmssSSS");
Date now = new Date();
return simpleDateFormat.format(now);
}
Related
I have two strings which can be seen as time stamps:
String min="2017-04-15 13:27:31";
String max="2017-04-15 13:40:01";
Assume we want to find out the time passed from first time stamp to the second one. If there was only the time and no date included, I could get it using my following code:
String[] partsMin=min.split(":");
String[] partMax=max.split(":");
int diffZero=Integer.parseInt(partMax[0])-Integer.parseInt(partsMin[0]);
int diffOne=Integer.parseInt(partMax[1])-Integer.parseInt(partsMin[1]);
int diffOTwo=Integer.parseInt(partMax[2])-Integer.parseInt(partsMin[2]);
diffInSec=diffZero*3600+diffOne*60+diffOTwo;
So here is the question. How to get the job done while there is a date within the time stamp?
I would construct LocalDateTime instances from it.
Then i would get the milliseconds from it and substract startTime from EndTime.
What is remaining are the milliseconds passed between the two. A DateTimeFormatter is helpful as well for this purpose.
String strMin = "2017-04-15 13:27:31";
DateTimeFormatter formatterTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTimeMin = LocalDateTime.parse(strMin, formatter);
String strMax = "2017-04-15 13:40:01";
LocalDateTime dateTimeMax = LocalDateTime.parse(strMax, formatter);
long minutes = ChronoUnit.MINUTES.between(dateMin, dateMaxto);
long hours = ChronoUnit.HOURS.between(dateMin, dateMax);
If you want to get the milliseconds:
long millisPassed = dateMax.toEpochMilli() - dateMax.toEpochMilli();
Use the java date time libraries (even the old Date class would be fine for this) to parse the string into a proper object.
Depending on the date time library you chose you can then look at the difference between them. The simplest would be something like:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date1 = sdf.parse(str1);
Date date2 = sdf.parse(str2);
long differenceInSeconds = (date2.getTime()-date1.getTime())/1000;
The new Java 8 time classes would also allow you to do this and would be better to learn going forwards. I can't remember the syntax for that off the top of my head though.
Did you try with replace all the other part of your String like this :
String[] partsMin = min.replaceAll("\\d+-\\d+-\\d+", "").trim().split(":");
String[] partMax = max.replaceAll("\\d+-\\d+-\\d+", "").trim().split(":");
Doing this in your code:
int diffZero=Integer.parseInt(partMax[0])
is the same as doing:
int diffZero=Integer.parseInt("2017-04-15")
that is generating an Exception(NumberFormatException)
you should better try to PARSE those strings min and max into a date
Edit:
you can inspect your code/ variables: and see that splitting to ":" is not giving you back the correct array since the element at index 0 is holding more information than you need...
but as I said before, you are going on the wrong path, dont re invent the wheel and look how practical will get using the APIs that java has for us:
String min = "2017-04-15 13:27:31";
String max = "2017-04-15 13:40:01";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTimeMin = LocalDateTime.parse(min, formatter);
LocalDateTime dateTimeMax = LocalDateTime.parse(max, formatter);
long days = ChronoUnit.DAYS.between(dateTimeMin, dateTimeMax);
long minutes = ChronoUnit.MINUTES.between(dateTimeMin, dateTimeMax);
System.out.println(days);
System.out.println(minutes);
use SimpleDateFormat to parse the date string, and do operation on Date result, you will get right value. This works well for date between '2017-02-28 23:59:59' and '2017-03-01 00:00:01'
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = format.parse("2017-02-28 23:59:59");
Date date2 = format.parse("2017-03-01 00:00:01");
long time1 = date1.getTime();
long time2 = date2.getTime();
long diff = time2 - time2; // should be 2000
I need to convert UTC time string I get into local time using following method,
String dateCreate = "2013-07-01T04:37:14.771468Z"
DateFormat dfParse = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss'Z'");
dfParse.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("Asia/Colombo"));
java.util.Date dateTime;
dateTime = dfParse.parse(dateCreate);
String dteCreate = df.format(dateTime);
Can someone plese give me a solution for this.? :)
EDIT: Now that I've checked it supports this easily, I'd strongly recommend that you use Joda Time. Its ISO-8601 parser works fine:
String dateCreate = "2013-07-01T04:37:14.771468Z";
DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
DateTime parsed = formatter.parseDateTime(dateCreate);
By default that will convert to the system default time zone, but you can change that behaviour with calls on DateTimeFormatter.
Joda Time is also a much cleaner API than the built-in one - you'll find any date/time code is easier to write and easier to read.
Look at your input data and your pattern:
String dateCreate = "2013-07-01T04:37:14.771468Z";
DateFormat dfParse = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss'Z'");
They don't match at all. You need something like:
// Don't use this directly!
DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'");
dfParse.setTimeZone(TimeZone.getTimeZone("UTC"));
Or:
// Don't use this directly!
DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSX");
The latter will cope with any ISO-8601 time zone; the former restricts to UTC.
Unfortunately, the above will end up with the wrong number of milliseconds as it will take all the microseconds to be milliseconds. I don't know of a way of avoiding this in Java... you may need to trim the string first. For example:
// Remove the sub-millisecond part, assuming it's three digits:
int firstPartLength = "yyyy-MM-ddTHH:mm:ss.SSS".length();
String noMicros = dateCreate.substring(0, firstPartLength) +
dateCreate.substring(firstPartLength + 3);
// Now we've got text without micros, so create an appropriate pattern
DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date date = dfParse.parse(noMicros);
Alternatively, if you know it's always going to end with "Z":
int firstPartLength = "yyyy-MM-ddTHH:mm:ss.SSS".length();
String noMicros = dateCreate.substring(0, firstPartLength);
DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
dfParse.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = dfParse.parse(noMicros);
This is irritating, and it would be nice to be able to tell Java to treat any digits after the dot as "fractions of a second" but I don't know of any way of doing that using SimpleDateFormat. Note that you wouldn't be able to represent the sub-millisecond value using just Date anyway.
This is xsd dateTime format. You should use javax.xml.bind.DatatypeConverter for that
Calendar c = DatatypeConverter.parseDateTime(lexicalXSDDateTime);
Note that for SmipleDateFormat S means number of milliseconds so it will parse 771468 as 771468 ms not 0.771468 sec which adds extra 771 secs to the result date
Formatting part is OK
I have a date inside a string, something like "12-December-2012".
How can I convert this into milliseconds (long)?
Using SimpleDateFormat
String string_date = "12-December-2012";
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
try {
Date d = f.parse(string_date);
long milliseconds = d.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
It’s about time someone provides the modern answer to this question. In 2012 when the question was asked, the answers also posted back then were good answers. Why the answers posted in 2016 also use the then long outdated classes SimpleDateFormat and Date is a bit more of a mystery to me. java.time, the modern Java date and time API also known as JSR-310, is so much nicer to work with. You can use it on Android through the ThreeTenABP, see this question: How to use ThreeTenABP in Android Project.
For most purposes I recommend using the milliseconds since the epoch at the start of the day in UTC. To obtain these:
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("d-MMMM-uuuu", Locale.ENGLISH);
String stringDate = "12-December-2012";
long millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter)
.atStartOfDay(ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
System.out.println(millisecondsSinceEpoch);
This prints:
1355270400000
If you require the time at start of day in some specific time zone, specify that time zone instead of UTC, for example:
.atStartOfDay(ZoneId.of("Asia/Karachi"))
As expected this gives a slightly different result:
1355252400000
Another point to note, remember to supply a locale to your DateTimeFormatter. I took December to be English, there are other languages where that month is called the same, so please choose the proper locale yourself. If you didn’t provide a locale, the formatter would use the JVM’s locale setting, which may work in many cases, and then unexpectedly fail one day when you run your app on a device with a different locale setting.
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse("12-December-2012");
long mills = date.getTime();
Take a look to SimpleDateFormat class that can parse a String and return a Date and the getTime method of Date class.
First convert string to java.util.Date using date formatter
Use getTime() to obtain count of millisecs from date
you can use the simpleDateFormat to parse the string date.
Easiest way is used the Date Using Date() and getTime()
Date dte=new Date();
long milliSeconds = dte.getTime();
String strLong = Long.toString(milliSeconds);
System.out.println(milliSeconds)
using simpledateformat you can easily achieve it.
1) First convert string to java.Date using simpledateformatter.
2) Use getTime method to obtain count of millisecs from date
public class test {
public static void main(String[] args) {
String currentDate = "01-March-2016";
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
Date parseDate = f.parse(currentDate);
long milliseconds = parseDate.getTime();
}
}
more Example click here
Try below code
SimpleDateFormat f = new SimpleDateFormat("your_string_format", Locale.getDefault());
Date d = null;
try {
d = f.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
long timeInMillis = d.getTime();
I have this time:
String myTime = "14:10";
Now I want to add 10 minutes to this time, so that it would be 14:20
How can I achieve this?
Something like this
String myTime = "14:10";
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Date d = df.parse(myTime);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.MINUTE, 10);
String newTime = df.format(cal.getTime());
As a fair warning there might be some problems if daylight savings time is involved in this 10 minute period.
I would use Joda Time, parse the time as a LocalTime, and then use
time = time.plusMinutes(10);
Short but complete program to demonstrate this:
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
LocalTime time = formatter.parseLocalTime("14:10");
time = time.plusMinutes(10);
System.out.println(formatter.print(time));
}
}
Note that I would definitely use Joda Time instead of java.util.Date/Calendar if you possibly can - it's a much nicer API.
Use Calendar.add(int field,int amount) method.
Java 7 Time API
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");
LocalTime lt = LocalTime.parse("14:10");
System.out.println(df.format(lt.plusMinutes(10)));
You need to have it converted to a Date, where you can then add a number of seconds, and convert it back to a string.
I used the code below to add a certain time interval to the current time.
int interval = 30;
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Calendar time = Calendar.getInstance();
Log.i("Time ", String.valueOf(df.format(time.getTime())));
time.add(Calendar.MINUTE, interval);
Log.i("New Time ", String.valueOf(df.format(time.getTime())));
You have a plenty of easy approaches within above answers.
This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.
String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
Output :
14:10
14:20
I would recommend storing the time as integers and regulate it through the division and modulo operators, once that is done convert the integers into the string format you require.
I have a problem parsing just the time string from my database
private static final String TIME_FORMAT = "HH:mm:ss";
public static final SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault());
And following the output:
String time = "17:17:57";
Date myParsedDate = timeFormat.parse(time); //forget the exception thing
//output of myParsedDate.toString = "Thu Jan 01 16:47:57 GMT+08:00 1970"
It seems as though theres a problem with the locale or something.. just a simple string.. Why is this so? i just want the date to be the having the time i need for my time picker.. gee..
Edit
Because i am using a static time format i decided to use my little helper method
public static Date getTimeFromTimeString(String timeString)
{
String[] splitStrings = timeString.split(":");
Date timeDate = new Date();
timeDate.setHours(Integer.parseInt(splitStrings[0]));
timeDate.setMinutes(Integer.parseInt(splitStrings[1]));
timeDate.setSeconds(Integer.parseInt(splitStrings[2]));
return timeDate;
}
Thanks for the help Jon Skeet.. I believe it is the TimeZone offset that is causing this.. .. ill just stick to my little method..
The problem is you're printing out the result of Date.toString() - which always shows the results in the system time zone. That's probably not what you want.
The Date itself has no concept of a time zone - it's just an instant in time.
I would suggest you use Joda Time if at all possible. That has a LocalTime which actually represents what you're parsing here.
EDIT: Just to reiterate what's in the comment... I suspect that the time zone in your DateFormat is not the same as the time zone used by Date.toString. For simplicity, it's probably worth setting the DateFormat's time zone to UTC, and then if you want to convert to a Calendar you should set that time zone to UTC as well before calling setTime(date).
Just do this:
Calendar c = Calendar.getInstance();
c.setTime(myParsedDate);
int hours = c.get(Calendar.HOUR);
int mins = c.get(Calendar.MINUTE);
int seconds = c.get(Calendar.SECOND);