How to get long value from this date format "MMM dd, yyyy" on blackberry - blackberry

I got response from Server as below
<reminder><text>Hello Dude!</text><date>June 2, 2011</date></reminder>
I parsed the info successfully. Now i need to add the info on blackberry reminder.
I used below code:
try
{
Event _event;
String Calenderevent = "Hello Dude.";
EventList eventList = (EventList) PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.WRITE_ONLY);
_event = eventList.createEvent();
long l= HttpDateParser.parse("June 2, 2011");
_event.addString(Event.SUMMARY, PIMItem.ATTR_NONE,Calenderevent);
_event.addDate(Event.START, PIMItem.ATTR_NONE, l);
RepeatRule rule = new RepeatRule();
rule.setInt(RepeatRule.FREQUENCY,RepeatRule.YEARLY);
_event.setRepeat(rule);
//If you need to repeat the event then use repeatrule.
_event.commit();
Dialog.alert("Calendar event success.");
}
catch (PIMException e)
{
Dialog.alert("Exception: "+e);
e.printStackTrace();
}
When I saw in Blackberry calendar, the info show in Dec 31, 2011
The problem occur is in below line.
long l= HttpDateParser.parse("June 2, 2011");
It returns -1 value.
How to get long value from this date format "MMM dd, yyyy" on blackberry.
Pls help me.

As Joel noticed, you date format is not supported by HttpDateParser. One possible solution would be to convert your date to one of formats that HttpDateParser supports and then parse it with parse() method.
This code converts your date to Wdy, Mon DD YYYY HHMMSS format first and then parses it.
String date = "June 2, 2011";
String time = "120000"; // desired time HHMMSS
long l = 0;
try {
StringBuffer sbDate = new StringBuffer();
// append WEEKDAY. weekday is not relevant for the HttpParser.
sbDate.append("Sun, ");
// remove comma after month
int commaIndex = date.indexOf(",");
sbDate.append(date.substring(0, commaIndex));
sbDate.append(date.substring(commaIndex+1));
sbDate.append(' ').append(time);
l=HttpDateParser.parse(sbDate.toString());
} catch (IndexOutOfBoundsException e) {
// the date is in wrong format
}
From the tests I made, Wdy is not taken into account by HttpDateParser. It returns the correct result with any valid weekday. This make sense for me, since what is really needed is DAY, MONTH and YEAR.

Related

Display local time zone abbreviation using DateFormatter

I have a DateFormatter that outputs the date in the format "2:00pm, Thu 18 Oct":
static func scheduleFormatter() -> DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.amSymbol = "am"
dateFormatter.pmSymbol = "pm"
dateFormatter.dateFormat = "h:mma, EE dd MMM"
return dateFormatter
}
I need to add in the local time zone abbreviation of the user so that the string appears like "2:00 pm GMT, Thu 18 Oct". How can I do that?
Look at the Unicode Date Formatting Patterns:
Probably you want the pattern v:
The short generic non-location format. Where that is unavailable, falls back to the generic location format ("VVVV"), then the short localized GMT format as the final fallback.
or z:
The short specific non-location format. Where that is unavailable, falls back to the short localized GMT format ("O").
Note that time zone names are connected to language and setting posix locale will probably break that.
You could also ask for the abbreviation directly and include it in your format explicitly:
"h:mma, '\(TimeZone.current.abbreviation() ?? "")' EE dd MMM"
To display the time zone you can simply add "zzz" in your dateFormat string. For example: "h:mma zzz, EE dd MMM"
public static Date getCurrentTimeStampDate(){
String currentDate = new SimpleDateFormat(""yyyy:MM:dd HH:mm:ss").format(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime());
SimpleDateFormat formater = new SimpleDateFormat(""yyyy:MM:dd HH:mm:ss");
try {
return formater.parse(currentDate);
} catch (ParseException e) {
return null;
}
}

Date formatting for next available date in Swift [duplicate]

This question already has answers here:
Convert string with unknown format (any format) to date
(2 answers)
Closed 5 years ago.
I'm currently downloading fixture lists for a sports app from a third party website that runs the league, so the data I have to work with is restricted.
I'm trying to implement a feature that displays the next upcoming fixture.
My problem is the dates being retrieved look like this:
"Sat 9th Sep 17" and "Sat 24th Mar 18" for example.
I've tried numerous date formats in the DateFormatter that I know of and can't find anything that uses this specific format.
If I try to use the Date from string method in the date formatter with one of the above strings I get a nil value.
I have an array of fixtures, each with their own dates. I need to compare each of these to the current date to figure out which is next in line.
My temporary fix for this was just to loop through the fixtures and as soon as one did not have a result to display that as the next fixture. Obviously this doesn't work when a game may not have been played for whatever reason.
What would be the best way to deal with this?
Basically you would just need to convert the current date to the same format as the date you get from your third party website (or the opposite) so you can compare them easily:
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EE MMM"
let firstPartStringDate = dateFormatter.string(from: currentDate)
dateFormatter.dateFormat = "yy"
let lastPartStringDate = dateFormatter.string(from: currentDate)
let day = Calendar.current.component(.day, from: currentDate)
let formatter = NumberFormatter()
formatter.numberStyle = .ordinal
guard let ordinalDay = formatter.string(for: day) else {
return
}
let finalDateString = firstPartStringDate + " \(ordinalDay) " + lastPartStringDate
print(finalDateString)
And for today's current date you would get the exactly same format as the one you get from the third-party website :
Sun Sep 17th 17
UPDATE: Here is how you could convert the String you get from the third-party website to a Date, and then compare it with the current date. This solves the problem of having the st, nd, rd and th inside the String at first.
// This is the string you get from the website
var webDateString = "Sat 9th Sep 17"
// First, remove the st, nd, rd or th if it exists :
if let stSubrange = webDateString.range(of:"st") {
webDateString.removeSubrange(stSubrange)
} else if let ndSubrange = webDateString.range(of:"nd") {
webDateString.removeSubrange(ndSubrange)
} else if let rdSubrange = webDateString.range(of:"rd") {
webDateString.removeSubrange(rdSubrange)
} else if let thSubrange = webDateString.range(of:"th") {
webDateString.removeSubrange(thSubrange)
}
// Now convert the string to a date :
dateFormatter.dateFormat = "EE MMM dd yy"
guard let formattedDate = dateFormatter.date(from: finalDateString) else {
return
}
// You can now compare formattedDate and the current date easily like so :
let currentDate = Date()
if formattedDate < currentDate {
// Do something interesting here :)
} else {
// Do something else!
}

Date format Convertion issue in swift

i could not convert string date into NSDate object.
Please check below code
let stringDate = "06:30 AM"
let formatter = NSDateFormatter()
formatter.dateFormat="hh:mm a"
let local = NSLocale(localeIdentifier: "en_US")
formatter.locale=local
let date = formatter.dateFromString(stringDate)
The output is as expected, and depending on what you're trying to achieve, you haven't really done anything wrong.
Your stringDate instance contains only information about a time of the day, not a date (the prior is also the only format your NSDateFormatter formatter is "interested" in). Hence, the following snippet produces the expected 06:30 AM output:
let stringDate = "06:30 AM"
let formatter = NSDateFormatter()
formatter.dateFormat="hh:mm a"
let local = NSLocale(localeIdentifier: "en_US")
formatter.locale=local
if let date = formatter.dateFromString(stringDate) {
print(formatter.stringFromDate(date)) // 06:30 AM
}
NSDate instances are defined, however, as single point in time (date and hour of the day), with reference to an absolute reference date:
NSDate objects encapsulate a single point in time, independent of
any particular calendrical system or time zone. Date objects are
immutable, representing an invariant time interval relative to an
absolute reference date (00:00:00 UTC on 1 January 2001).
From the language reference for NSDate.
Hence, in addition to a time of day, NSDate instances include also a date (even if this is not, in your case, used or displayed). When you assign a value to date above, the Swift playground displays the time of day of the correct date; the latter offset by 06:30 from the absolute reference date, 2000-01-01 00:00:00. If we modify the example above to print all details in the final print statement, we see this more clearly:
// ...
if let date = formatter.dateFromString(stringDate) {
formatter.dateStyle = .FullStyle
formatter.timeStyle = .FullStyle
print(formatter.stringFromDate(date))
/* Saturday, January 1, 2000 at 6:30:00 AM Central European Standard Time */
}
(Addition with regard to your comments below)
Note the difference of printing the date object itself (e.g. print(date) above) and printing a ** formatted string representation** of the date using your formatter (e.g. print(formatter.stringFromDate(date))). The prior just prints the .description property of your date, which is an default-formatted string representation of the contents of object itself rather than a controlled formatted output of the date:
Declaration
var description: String { get }
Description
A string representation of the date object. (read-only)
The representation is useful for debugging only.
There are a number of options to acquire a formatted string for a date
including: date formatters (see NSDateFormatter and Data Formatting
Guide), and the NSDate methods descriptionWithLocale:,
dateWithCalendarFormat:timeZone:, and
descriptionWithCalendarFormat:timeZone:locale:
Refer to my code blocks above to see how you can print the formatted date using your NSFormatter.

NSDate and string without timezone information

I am parsing some XML that is returned by a web service. The string: 2015-12-24T12:00:00 is found in the fromTimestamp with no timezone. The "geniuses" (I don't mean that) keeps the timezone information in a own field in the XML in minutes. So 300 means GMT+05:00.
I have been reading a lot about NSDate and all this timezone stuff and I know that NSDate don't care about timezones, thats NSDateFormatter job.
However, in order to "convert" the timestamp without the timezone so that the value in NSDate represents a GMT time I add the GMT+05:00 to the string so it becomes 2015-12-24T12:00:00 +05:00. This is how it must be done right? Without adding the timezone when you convert from string to date the NSDate thinks the value is the GMT time? Thats the part I don't understand about it. It would be wrong to just convert the string without that timezone information because NSDate wouldn't be able to subtract 5 hours from the value inside NSDate? Is that correct? I am having a hard time explaining it.
Your assessment is correct and your solution is one of two possible solutions.
To ensure the date string is properly converted to an NSDate, you can do one of two things:
You need to ensure the date string has timezone information included and the date formatter's format string includes the proper format specifier for the timezone. This is what you describe in your question.
You leave the date string as you have it, without timezone information. But you set a specific timezone on the date formatter based on the timezone field you get from the XML.
Either approach will give you the proper NSDate.
Update: My second approach is shown in the answer by Martin R.
It may be simpler to set the time zone of the date formatter
explicitly. Example (error checking omitted for brevity):
let fromTimestamp = "2015-12-24T12:00:00"
let timeZoneInfo = "300"
let fmt = NSDateFormatter()
fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let secondsFromGMT = Int(timeZoneInfo)! * 60
fmt.timeZone = NSTimeZone(forSecondsFromGMT: secondsFromGMT)
let date = fmt.dateFromString(fromTimestamp)
I found it more convenient to wrap Martin's approach as an extension of the String class. It also prepends it with current timestamp and writes text ta a debugger output.
Swift 5:
"Hello world".log()
2019-09-05 12:18:10 Hello world
extension String {
func log() {
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd' 'HH:mm:ss"
let formattedString = "\(fmt.string(from: Date())) \(self)"
print(formattedString)
let log = URL(fileURLWithPath: "log.txt")
do {
let handle = try FileHandle(forWritingTo: log)
handle.seekToEndOfFile()
handle.write((formattedString+"\n").data(using: .utf8)!)
handle.closeFile()
} catch {
print(error.localizedDescription)
do {
try self.data(using: .utf8)?.write(to: log)
} catch {
print(error.localizedDescription)
}
}
}
}

Zoned dateTime to UTC Time - LocalDateTimePattern throws exception

I am trying to obtain the UTC time from a zoned datetime using LocalDateTime pattern in NodaTime using the below code.
public string getUtcTimeFromZonedTime(string dateTimeString, string timeZoneID,
string dateTimePattern, bool isDateTime)
{
if (string.IsNullOrEmpty(dateTimePattern))
{
if (isDateTime)
{
dateTimePattern = "M/dd/yyyy HH:mm:ss tt";
}
else
{
dateTimePattern = "M/dd/yyyy";
}
}
var pattern = LocalDateTimePattern.CreateWithInvariantCulture(dateTimePattern);
var parseResult = pattern.Parse(dateTimeString);
if (!parseResult.Success)
{
// throw an exception or whatever you want to do
}
var localDateTime = parseResult.Value;
var timeZone = DateTimeZoneProviders.Tzdb[timeZoneID];
// TODO: Consider how you want to handle ambiguous or "skipped" local date/time
// values. For example, you might want InZoneStrictly, or provide your own custom
// handler to InZone.
var zonedDateTime = localDateTime.InZoneLeniently(timeZone);
return zonedDateTime.ToDateTimeUtc().ToString();
}
I get an exception during Parsing during below mentioned scenarios-
1) If pattern is like "MM/dd/yyyy HH:mm:ss tt" and the DateTime string is something like "5/28/2013 1:02:ss PM"
2) If pattern is like "MM-dd-yyyy HH:mm:ss tt" and the DateTime string is something like "5/28/2013 1:02:ss PM"
For the first case, it will work if I change my pattern to "M/dd/yyyy HH:mm:ss tt", but i will end up losing the leading zero. Second case will work if I change the pattern to "MM/dd/yyyy HH:mm:ss tt"
Is there any alternative way for getting the UTC values or am I doing something wrong over here.
1) If pattern is like "MM/dd/yyyy HH:mm:ss tt" and the DateTime string is something like "5/28/2013 1:02:ss PM"
Yes, because you've specified that you'll give it a two-digit hour, and you've only given one digit. Note that if you're using an AM/PM designator, you probably want h rather than H anyway.
2) If pattern is like "MM-dd-yyyy HH:mm:ss tt" and the DateTime string is something like "5/28/2013 1:02:ss PM"
Yes, because you've specified that you want - as the separator, but you're using / in the text.
I suspect you want:
dateTimePattern = "M/dd/yyyy h:mm:ss tt";
Note that this has nothing to do with converting to UTC - it's just the parsing to LocalDateTime that's causing you problems.

Resources