Simple code:
func main() {
date := "2020-12-23T16:39:24.362+06:00"
t, _ := time.Parse("2006-01-02T15:04:05.000+06:00", date)
fmt.Printf("t = %s", t)
}
Result is t = 2006-12-23 16:39:24.362 +0000 UTC
Link to playground: https://play.golang.org/p/3U6CzIrrMsM
Where I made a mistake?
The reference time has -0700 time zone. Quoting from time.Parse():
Parse parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time, defined to be
Mon Jan 2 15:04:05 -0700 MST 2006
would be interpreted if it were the value; it serves as an example of the input format. The same interpretation will then be made to the input string.
With this change it works:
date := "2020-12-23T16:39:24.362+06:00"
t, err := time.Parse("2006-01-02T15:04:05.000-07:00", date)
fmt.Println(err)
fmt.Printf("t = %s", t)
And outputs (try it on the Go Playground):
<nil>
t = 2020-12-23 16:39:24.362 +0600 +0600
Related
I'm trying to parse a date string into a Date class. I'm using SwiftDate for this. But when I tried to parse it, it returned 1 day less than the value in the string. Here are some examples:
let birthString = "1996-10-08"
self.birthday = Date(birthString, format: "yyyy-MM-dd", region: Region.current)
//Result: self.birthday = 1996-10-07 17:00:00 UTC
let expiredString = "2019-09-30"
self.membershipExpiredDate = Date(expiredString, format: "yyyy-MM-dd", region: Region.current)
//Result: self.membershipExpiredDate = 2019-09-29 17:00:00 UTC
How do I fix this error? Thanks.
SwiftDate uses regions, and you are setting the region to Region.current. The date is correct and you can check that using the .timeIntervalSince1970 property. What happens is that when you print the date (which is actually just a TimeInterval, aka Double, a specific point in time, independent of any calendar or time zone), it's printing its description property, with the default time zone UTC (You can see it in your output 17:00:00 UTC).
To print a date using your current locale, use this instance method:
print(date.description(with: Locale.current))
I'm getting a string representation of a date from a json that looks like the following:
let dateString = "2016-12-31T00:10:00+01:00"
In order to model it as a Date object I'm using a date formatter like so:
let dateForm = DateFormatter()
dateForm.locale = Locale(identifier: "fr_FR")
dateForm.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateForm.timeZone = TimeZone.current
When I turn it into a Date, my Playground output is correct:
let date = dateForm.date(from: dateString)
=> Output: "Dec 31, 2016, 12:10 AM"
But if I try to print this exact same object (date) I get the following output:
print(date!)
=> Output: "2016-12-30 23:10:00 +0000\n"
My question is: How can I be sure that I'm dealing with the correct date (by correct I mean with my local time zone (GMT+01)) ?
When you print the date output 2016-12-30 23:10:00 +0000 and your GMT is +00:00
but when you get the string from date it will return string as per your given format And your Locale (fr_FR) output 2016-12-31T00:10:00+01:00 and your GMT is +01:00
if you want to date from string then
date output = your string date - (your GMT)
In your case
2016-12-30 23:10:00 = 2016-12-31 00:10:00 - (+01:00)
In one of my app I have date and time for multiple data fetching from server. I have shown this in tableview. Now from this I have to find some idle time for particular row by some condition by previous and next row's date and time difference. Something like departure and arrival of vehicle and idle time in between. I will show you the issued code where the issue occurs (only for I have both valid date).
let dFormater = NSDateFormatter()
dFormater.dateFormat = "ddMMMYYHHmm"
dFormater.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dFormater.timeZone = NSTimeZone(name: "GMT")
dFormater.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
print(startDate)
print(endDate)
if let validFdate : NSDate = dFormater.dateFromString(startDate) {
if let validLdate : NSDate = dFormater.dateFromString(endDate) {
print(validFdate)
print(validLdate)
let minutes = validLdate.minutesFrom(validFdate)
print("LO P & N \(indexPath.row)= \(minutes)")
let hour = minutes/60
let min = minutes%60
let fullTime = NSString.init(format: "%02d:%02d", Int(hour),Int(min))
strToReturn = fullTime as String
}
}
And log for this is like
03JUN161411
04JUN160542
2015-12-20 08:41:00 +0000
2015-12-20 00:12:00 +0000
LO P & N 0= -509.0
04JUN160931
05JUN160506
2015-12-20 04:01:00 +0000
2015-12-19 23:36:00 +0000
LO P & N 0= -265.0
07JUN160530
07JUN162127
2015-12-20 00:00:00 +0000
2015-12-20 15:57:00 +0000
LO P & N 2= 957.0
08JUN160049
08JUN161616
2015-12-19 19:19:00 +0000
2015-12-20 10:46:00 +0000
LO P & N 1= 927.0
Now From this logged output, you can see that thought there is valid date in first two still it show wrong output as there are different date and in last two output there is perfect output as both date are of same date. And also why it changes date month and year. See
03JUN161411
2015-12-20 08:41:00 +0000
(I have asked another question only for date here)
Your date format is incorrect.
dFormater.dateFormat = "ddMMMYYHHmm"
Capital Y is the year in week-of-year based calendars. You need to use lower case Y:
dFormater.dateFormat = "ddMMMyyHHmm"
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 );
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.