I am fairly new to Groovy (but already loving it). I am not new to coding but haven't had much experience so far.
What am I doing?
I am extracting certain information from an excel file to create a XML (SOAP) message from it to forward it to a web-service. Everything works fine so far except the Date conversion.
I am saving the string date to a var
odate = 'Wed Oct 31 00:00:00 CET 2012'
I need to reformat this Date into something like
"10/31/2012 10:09:00" (MM/dd/yyyy HH:mm:ss)
I have tried to parse the date as mentioned in another question but all I get is an exception.
String odate = 'Wed Oct 31 00:00:00 CET 2012'
def parsedodate = new Date().parse('E MMM dd H:m:s z yyyy', odate)
println parsedodate.format('MM/dd/yyyy h:m:s')
Exception thrown
31.10.2012 10:18:25 org.codehaus.groovy.runtime.StackTraceUtils sanitize
WARNUNG: Sanitizing stacktrace:
java.text.ParseException: Unparseable date: "Wed Oct 31 00:00:00 CET 2012"
Now after a little reading and some rounds of trial & error I found out that somehow the parse method seems to only interpret german dates. The following works after manually changing the string date to a german format (which is whre I am located).
String odate = 'Mi Okt 31 00:00:00 2012' //Mi = Wednesday, Okt = October, removed timezone
def parsedodate = new Date().parse('E MMM dd H:m:s yyyy', odate) // removed the z
println parsedodate .format('MM/dd/yyyy h:m:s')
However, I need the parser to accept the english date format.
What do I do (wrong)?
Whole groovy solution for your problem would be:
import java.text.SimpleDateFormat
odate="Wed Oct 31 00:00:00 CET 2012"
englishPattern="E MMM dd H:m:s z yyyy"
SimpleDateFormat englishDateFormat = new SimpleDateFormat( englishPattern , Locale.ENGLISH);
//SimpleDateFormat germanDateFormat = new SimpleDateFormat( germanPattern , Locale.GERMAN);
Date englishDate = englishDateFormat.parse( odate );
//Date germanDate = germanDateFormat.parse( odate );
String englishOutput = englishDate .format( englishPattern );
//String germanOutput = germanDate .format( germanPattern );
englishDate.format("MM/dd/yyyy hh:mm:ss")
You will need to use some Java to access Locale aware SimpleDateFormat instance.
SimpleDateFormat englishDateFormat = new SimpleDateFormat( englishPattern , Locale.ENGLISH);
SimpleDateFormat germanDateFormat = new SimpleDateFormat( germanPattern , Locale.GERMAN);
Date englishDate = englishDateFormat.parse( odate );
Date germanDate = germanDateFormat.parse( odate );
String englishOutput = englishDate .format( englishPattern );
String germanOutput = germanDate .format( germanPattern );
Related
I am working with a series of string representations of timestamps returned by time.asctime() in Python. The documentation states:
Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string of the following form: 'Sun Jun 20 23:21:05 1993'. The day field is two characters long and is space padded if the day is a single digit, e.g.: 'Wed Jun 9 04:26:40 1993'.
I've referenced Unicode Technical Standards to determine how I can instruct an instance of Swift's DateFormatter how to interpret the string and create a Date.
The UTS is very clear, but my Date object still unwraps to nil:
let dateAsString = measurement[2]
print("Date as string: \(dateAsString)")
let df = DateFormatter()
df.dateFormat = "E MMM dd HH:mm:ss y"
let date = df.date(from: dateAsString)
print("Date: \(String(describing: date))")
Output:
Date as string: Thu Oct 20 17:53:06 2022
Date: nil
Date as string: Thu Oct 20 17:53:06 2022
Date: nil
Date as string: Thu Oct 20 17:53:16 2022
Date: nil
When printing dateAsString to console output, I did not notice that there is a single trailing whitespace after the year. Adjusting the Unicode format string to the following solved the problem:
df.dateFormat = "EEE MMM d HH:mm:ss y " // <- observe the extra space
This question already has answers here:
NSDateFormatter doesn't show time zone abbreviation for "Asia/Kolkata" for the "z" or "zzz" specifier, just the GMT offset
(1 answer)
What is the best way to deal with the NSDateFormatter locale "feature"?
(4 answers)
Closed 5 years ago.
I need to convert the following date string in to a Date in Swift 3.
Fri Dec 09 16:18:43 AMST 2016
Here is the code that i have been using, but it's getting cash on this particular date string conversion. (This date was logged on Android using new Date().toString() method.)
static func formatDate(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
//Works for "Fri Sep 16 10:55:48 GMT+05:30 2016"
var myDate = dateFormatter.date(from: date)
// My date returns nil on "Fri Dec 09 16:18:43 AMST 2016"
dateFormatter.dateFormat = "dd/MM/yyyy"
return "\(dateFormatter.string(from: myDate!))"
}
There are both type of strings in the database. I tried with various types of Timezone formats (z/zz/zzz/zzzz/zzzzz) but always myDate returns nil.
Any help would be appreciated.
Thanks In Advance.
Apple doc for TimeZone(abbreviation:):
In general, you are discouraged from using abbreviations except for unique instances such as “GMT”. Time Zone abbreviations are not standardized and so a given abbreviation may have multiple meanings.
Does AMST represents "Amazon Summer Time" (UTC-3) or "Armenia Summer Time" (UTC+5)? See: https://www.timeanddate.com/time/zones
That's probably why it can't detect the proper timezone to use.
Solutions I can propose:
If you know which timezone AMST is:
replace AMST by UTC-3 or UTC+5 in the date string
remove AMST from the date string and use dateFormatter.timeZone = TimeZone(secondsFromGMT: -3 or 5 * 3600)
Have your source output a more precise timezone.
Note the following code, where AMST is understood correctly:
let df = DateFormatter()
df.locale = Locale.init(identifier: "pt_BR") // assuming AMST is Amazon Summer Time (UTC -3)
df.dateFormat = "HH:mm:ss z"
print(df.date(from: "16:18:43 AMST")) // Optional(2000-01-01 19:18:43 +0000)
But as soon as you include English day or month names (e.g. Fri or Dec) it will produce nil (because they aren't in Portuguese).
I am using this following way while doing an export to excel
alasql.fn.Date = Date;
alasql('SELECT new Date(mydateString) AS CUSTOM_DATE INTO XLS("' + filename + '.xls",{headers:true}) FROM ?', [items]);
Those above lines are printing in this below date format
Sat Jun 06 2015 00:00:00 GMT-0500 (Central Daylight Time)
but I want to format mydateString to this below format
MM-DD-YYYY hh:mm:ss
How can I do that?
I did this below instead and create my own format for date
alasql.fn.datetime = function(dateStr) {
var date = new Date(dateStr);
return date.toLocaleString();
};
alasql('SELECT datetime(mydateString) AS CUSTOM_DATE INTO XLS("' + filename + '.xls",{headers:true}) FROM ?', [items]);
In iOS, I am using a NSDateFormatter with the DateFormat EEE, dd MMM yyyy HH:mm:ss z.
The String Sat, 29 Aug 2015 12:34:36 EDT does not work and gives back nil when given to the function .dateFromString(). The exact same string with GMT (Sat, 29 Aug 2015 12:34:36 GMT) gives me the correct date, though.
What am I missing here?
So the problem was that the locale I was using wasn't a usual one. I live in Germany and use English as my system language, so the Locale was one with the identifier en_DE. Both de_DE and en_US work with the usual Time Zones (Like EDT), but the unusual en_DE doesn't work with all of them. So the fix was to use en_US as the locale.
Hopefully this should work, I'm in New Zealand but set locale to "EDT"
let string = "Sat, 29 Aug 2015 12:34:36 EDT"
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "EDT")
formatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss z"
let localDate = formatter.dateFromString(string)
I having a problem when convert String to Date in Blackberry SDK. Please support for me.
This is my code:
String date = "Mon May 09 09:00:00 GMT 2011";
Date formatter = new Date();
formatter.setTime(HttpDateParser.parse(date));
SimpleDateFormat dateFormat = new SimpleDateFormat(formatStr);
string dateString = dateFormat.format(formatter);
purpsoe of the function is format date MMM dd, YYYY.
But after i run the function, it will return result that I unexpected.
Expected: May 09, 2011
UnExpected : Jan,01,1970.
I suspect the "Mon May 09 09:00:00 GMT 2011" is not a supported by HttpDateParser date format. Since the HttpDateParser.parse() does not throw an exception, I guess it simply return 0 in case of an unsupported format.