It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I was wondering if java comes with a built in way to parse times/dates like this one:
5m1w5d3h10m15s
It's 5 months, 1 week, 5 days, 3 hours, 10 minutes, 15 seconds.
Yes, it's called SimpleDateFormat, you just have to define your pattern.
As you didn't (voluntarly?) precise the year, I added one :
DateFormat df = new SimpleDateFormat("M'm'W'w'F'd'H'h'm'm's's'yyyy");
System.out.println(df.parse("5m1w5d3h10m15s"+"2012"));
Of course there are some libraries available (many people redirect to Joda, which is better than the standard and confusing java libraries) but as your question is about "if java comes with a built in way to parse times/dates", the answer is a clear yes.
You probably want to parse this into a time period. rather than into a Date, unless your input looks like "2012y10m8d" etc. Expect to encounter many problems if you try to represent a period of time as a java.util.Date. Trust me, I've been down that path before.
Instead consider using Joda time for time periods. See this question for details: How do I parse a string like "-8y5d" to a Period object in joda time
HumanTime looks interesting too.
I would first reverse the string. Then, I would tokenize the string into 6 numeric, separate parts -- months, weeks, days, hours, minutes, seconds. I'd store each token in an array and treat each element separately: a[0] = seconds, a[1] = minutes, ... a[5] = months. That's the most intuitive way I can think of offhand since I can't recall any library that does this for you. And of course, you didn't specify what you mean by "parse."
I dont know about that specific format... but i suggest you take a look at this
also, it wouldn't be too difficult to build your own parser...
You can refer to this post for ideas:
Java date format - including additional characters
And of course the SimpleDateFormat class for reference.
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Using SimpleDateFormatter class will help you convert your string into a date. Using Joda time PeriodFormatter will allow you convert/express a period instead of a date. Eg. you will be able to express and parse something like: 15m1w5d3h10m15s too.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I want to see a month which contains whole days.
private void createRandomData(InMemoryCursor cursor) {
List<Object[]> data = new ArrayList<>();
Calendar today = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
today.set(Calendar.HOUR_OF_DAY,0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
mStart = (Calendar) today.clone();
mStart.add(Calendar.SEPTEMBER, -5);
while (mStart.compareTo(today) <= 0) {
data.add(createItem(mStart.getTimeInMillis()));
mStart.add(Calendar.SEPTEMBER, 1);
}
cursor.addAll(data);
}
When I write Calendar.SEPTEMBER(or other months), I see red line on Calendar.SEPTEMBER which contains:
Must be one of: Calendar.ERA, Calendar.YEAR, Calendar.MONTH, Calendar.WEEK_OF_YEAR, Calendar.WEEK_OF_MONTH, Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH, Calendar.AM_PM, Calendar.HOUR, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND, Calendar.ZONE_OFFSET, Calendar.DST_OFFSET less... (Ctrl+F1)
This inspection looks at Android API calls that have been annotated with various support annotations (such as RequiresPermission or UiThread) and flags any calls that are not using the API correctly as specified by the annotations. Examples of errors flagged by this inspection:
Passing the wrong type of resource integer (such as R.string) to an API that expects a different type (such as R.dimen).
Forgetting to invoke the overridden method (via super) in methods that require it
Calling a method that requires a permission without having declared that permission in the manifest
Passing a resource color reference to a method which expects an RGB integer value.
...and many more. For more information, see the documentation at developer.android.com/tools/debugging/annotations.html
When I run it despite the red line, It shows complicated dates like:
see
I use this library from GitHub:https://github.com/jruesga/timeline-chart-view
Is problem related to library? or It is about Java calendar?
As explained in #Michael's answer, you can't use Calendar.SEPTEMBER in the add method.
If you want to add or subtract a specified number of months, just use Calendar.MONTH. If you want to add/subtract days, you use Calendar.DAY_OF_MONTH and so on.
The Calendar API might be confusing sometimes (most times, IMO), and has lots of problems and design issues.
In Android, there's a better alternative: you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. To make it work, you'll also need the ThreeTenABP (more on how to use it here).
As you're getting a Calendar in the default timezone, a good candidate for replacement is a org.threeten.bp.ZonedDateTime (it represents a date and time in a specific timezone). First I use the now() method (that takes the current date/time at the JVM default timezone). Then I use a org.threeten.bp.LocalTime to set the time to midnight.
I also use the minusMonths method to get a date 5 months before the current date, and inside the loop I use the toInstant() method, to get the millis value, and the plusMonths method to get the next month:
// get today at default timezone, at midnight
ZonedDateTime today = ZonedDateTime.now().with(LocalTime.MIDNIGHT);
// 5 months ago
ZonedDateTime start = today.minusMonths(5);
while (start.compareTo(today) <= 0) {
data.add(createItem(start.toInstant().toEpochMilli()));
start = start.plusMonths(1);
}
If you want to add/subtract minutes instead of months, for example, you can use the methods minusMinutes and plusMinutes. There are other methods for another units as well (such as hours, days, and so on), check the javadoc to see all the options.
The problem of using the default timezone is that it can be changed without notice, even at runtime, so it's better to always make it explicit which one you're using.
With Calendar, you can use TimeZone.getTimeZone(zoneName):
Calendar todayCal = Calendar.getInstance(TimeZone.getTimeZone("Europe/London"), Locale.getDefault());
And with ThreeTen Backport, you can use ZoneId.of(zoneName):
ZonedDateTime today = ZonedDateTime.now(ZoneId.of("Europe/London")).with(LocalTime.MIDNIGHT);
In the example above, I used Europe/London, but you can change it to any timezone you want. The API uses IANA timezones names (always in the format Region/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds() or TimeZone.getAvailableIDs().
You are using an incompatible option. The first parameter of Calendar.add() is a Unit of Time (Day, Week, Hour etc) as defined by the possible options outlined in the error. Calendar.SEPTEMBER is not a unit of time, it is a convenience constant representing the MONTH of September that is typically used in the set() method instead.
Assuming you're iterating through months, you'll need Calendar.MONTH instead.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to get data from a website, and when I tried to get the date of a post (expected: 13/06/2014 11:55), i got:
23377855
Can someone help me to convert this number to a date? Thanks!
You can use the standard Java Date API:
long yourNumber = 23377855;
Date date = new Date(yourNumber);
Or you can use Joda Time library, provides much better overall functionality than Java Date API:
long yourNumber = 23377855;
DateTime dt = new DateTime(yourNumber);
Java is expecting milliseconds:
java.util.Date time= new java.util.Date((long)urDateNum*1000);
So you must multiply by 1000
Docs say:
Allocates a Date object and initializes it to represent the specified
number of milliseconds since the standard base time known as "the
epoch", namely January 1, 1970, 00:00:00 GMT.
Note:
The cast to long is very important in this situation. Without it the integer overflows.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I need to retreive intervals between start date , end date for every 30 minutes.
Ex:If my start date is 2011-12-10-10:00:00 and end date is 2011-12-11-10:00:00
I need to populate the intervals between these two dates in an array.
In JavaScript:
var dates = [],
start = new Date("2011-12-10T10:00:00Z"),
end = new Date("2011-12-11T10:00:00Z"); // make sure the format is parsed by all browsers - or use epoch timestamps
for (var i = new Date(start); i < end; i.setMinutes(i.getMinutes()+30))
dates.push(new Date(i));
You can easily do this with JODA. Use the Interval.withDurationAfterStart() will give you an interval after the start time. Now create a loop that adds the interval to an array, and then gets the next interval using the end time of the previous interval (until you are >= the end instant).
The resulting array will hold your interval list.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Why does Java make it not obvious how to get the day of the month from a Date object?
.getDay() was deprecated, it is recommended to use Calendar.get(Calendar.MONTH)
This makes little sense to me and I was curious what the rationale behind this deprecation is.
I have a Date object and I just want the day. It's the most natural thing ever and I can't invoke it. This design is wrong and therefore my code is not working the way it should:
private String getIngivningsDag() {
return ""+ingivningsDatum.getDate();
}
private String getIngivningsMonth() {
return ""+ingivningsDatum.getmonth();
}
private String getIngivningsYear() {
return ""+ingivningsDatum.getYear();
}
Update
here's the "solution":
public String getIngivningsDag() {
Calendar cal = Calendar.getInstance();
cal.setTime(ingivningsDatum);
return cal.get(Calendar.DAY_OF_WEEK_IN_MONTH)+"";
}
Here's how it should look simple and good without the design errors of Java and using method parameters instead of strange Class methods and factories:
public String getIngivningsDag() {
return ingivningsDatum.getDay(Calendar.GREGORIAN, "SE");
}
The Date means a moment of time, but exact day/month/time/etc is different in different calendars and timezones. So, to know what day is a particular timestamp, you should use Calendar Timezone and DateFormat. E.g. jdk has at least two calendars implementation - BuddistCalendar and GregorianCalendar. Default calendar depends on user's preferences.
Also, have a look at Jodatime library - it is has more features and makes more sense to manage dates in Java.
Not only that method, most of the methods of Date class and some constructors are now deprecated. You have to use Calendar class to get DAY, or MONTH from your Date object.
However, I would suggest you to try out Joda-Time API, that will make you much more happier, because, even Calendar class is a bit inconsistent when it comes to indexing of MONTH, which starts from 0 in it.
But, still, as for your current problem, you can convert your Date object to a Calendar instance using: -
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.MONTH));
From the docs:
Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.
Consider also the definition of a Date
The class Date represents a specific instant in time, with millisecond precision.
Adding calendar functionality to it arguably violates the single-responsibility principle.
java.Date is simply used to store the number of Milliseconds since Jan 1st 1970. If you want to have Calendar functionality like getDay() or dayOfWeek() you have to user the Calendar class.
The easiest solution is not to find why it was done but use Joda-Time.
first of all, getting angry saying design is wrong does not help anything.
second, Calendar.getDay(Calendar.MONTH) is not a static method. To access compounds of Date you use Calendar class in three steps:
create Calendar instance by invoking Calendar cal = Calendar.getInstance()
set your date to Calendar instance by invoking Calendar.setTime(date)
get month by invoking cal.get(Calendar.MONTH)
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
hi im trying to convert a date value in milliseconds granuality into java Date using
new Date( millsecs)
the converted value i get is 3 hours behind what it is supposed to be.
I tried using online tools to conver the millisec value i have and it convert to correct date.
Can some one point out what im missing!!!
thnx
A java.util.Date does not have an hour -- at least not in the way that you probably mean. Try the following, and you'll see that the date simply is a point in time that you can specific as X milliseconds since epoch:
long millisec = System.currentTimeMillis();
Date date = new Date(millisec);
long millisec2 = date.getTime();
If I print this date in New York City's time zone, it will correspond to some hour of the day. If I print the same date in GMT, then the hour will be four larger. You probably are printing the value in such a way that you see the same time zone effect.
Think of a date as a point in time. That's a specific number of milliseconds since epoch. Let's pick 3PM PDT as our point in time. This corresponds to 6PM EDT. In other words, all three of those values (millseconds since epoch, 3PM PDT, and 6PM EDT) occupy the same spot on on a timeline.
Or, here's another explanation. 3PM PDT on some day is NOT the same as 3PM EDT on that day. Let's say 3PM PDT corresponds to M milliseconds since epoch. Then, 3PM EDT = M - 10,800,000 milliseconds (that's the number of milleseconds in three hours).