I am trying to parse a string I return from a MySQL Date datatype as a date locally. However everytime I try to parse it with a DateFormatter() in Swift 3, the result date is two days off.
Here is an example of the date string returned from the server:
"Sat Dec 31 2016 00:00:00 GMT-0800 (PST)"
I try to use the DateFormatter() to capture that information in the following format string:
let DatFormatServerTwo = "EEE MMM dd yyyy HH':'mm':'ss zzzZ '('zzz')'"
Then I use it like this:
static func stringDateToDateTwo(dateString: String, timeZone: TimeZone = TimeZone.current) -> Date {
dateFormatter.dateFormat = DateFormatServerTwo
dateFormatter.timeZone = timeZone
return dateFormatter.date(from: dateString) ?? Date()
}
where dateFormatter is assigned to a DateFormatter()
I think the problem is that there is an offset with the timezone and I am not capturing that information properly. I get the desired date by chopping off parts of the date string namely as soon as the TimeZone stuff enters into the picture. I don't want to do that everytime though because it is messy.
Here is how I chop the string to get the date that I want from the server:
var holidayDateArray = holidayDate.characters.split{$0 == " "}.map(String.init)
var count = 0
var newString = ""
for substring in holidayDateArray {
if count < 5 {
newString.append(substring)
} else {
break
}
count += 1
}
And then I format like this:
static let DateFormatServerTwo = "EEEMMMddyyyyHH':'mm':'ss"
One issue is there is no format specifier for a timezone in the format GMT-XXXX. There is one for GMT-XX:XX but you don't have that format. So this solution is to treat the GMT as a literal and just parse the -XXXX part using the Z specifier. The end result is the same.
Also note there is no need to quote punctuation, just letters that are to be treated literally. There is also no need to set the formatter's timezone since you will be getting timezone info from the date string.
There is no need to process the string at all. Just use the correct format:
let str = "Sat Dec 31 2016 00:00:00 GMT-0800 (PST)"
let fmt = DateFormatter()
fmt.dateFormat = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z (z)"
let dt = fmt.date(from:str)
This gives the correct result for dt for the given string.
Try the following in a Playground:
let str = "Sat Dec 31 2016 00:00:00 GMT-0800 (PST)"
let fmt = DateFormatter()
fmt.dateFormat = "EEE MMM dd yyyy HH':'mm':'ss zzzZ '('zzz')'"
let dt = fmt.date(from:str)
You will notice that the date is nil.
If you remove the extra timezone information from the date string, and format the date formatter string accordingly:
let str = "Sat Dec 31 2016 00:00:00 -0800"
let fmt = DateFormatter()
fmt.dateFormat = "EEE MMM dd yyyy HH':'mm':'ss ZZZZ"
let dt = fmt.date(from:str)
You'll get: Dec 31, 2016, 1:30 PM
Incidentally, you don't need the quotes around the colons in the date format. So you can actually have the date format as:
fmt.dateFormat = "EEE MMM dd yyyy HH:mm:ss ZZZZ"
If the date string is consistent in how the date is laid out, you can easily remove the GMT and time zone within the quotes by doing something like:
let str = "Sat Dec 31 2016 00:00:00 GMT-0800 (PST)"
let newStr = str.replacingOccurrences(of:"GMT", with:"").replacingOccurrences(of:"\\(.*?\\)", with:"", options: String.CompareOptions.regularExpression)
let fmt = DateFormatter()
fmt.dateFormat = "EEE MMM dd yyyy HH:mm:ss ZZZZ"
let dt = fmt.date(from:newStr)
When done this way, the date does appear to come through correctly. Let me know if your results are different when you try this in a Playground.
Related
I have time values in JSON like so:
"start_date": "2018-04-20 9:00:00 -08:00",
"end_date": "2018-4-20 12:00:00 -08:00"
I want to format the dates so that when I put them in a list, I can show for example:
Fri 4/20 9-12 PM
Here's a quick sample on how to do this using date components:
func toDate(start: String, end: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let startDate = dateFormatter.date(from: start)!
let endDate = dateFormatter.date(from: end)!
let calendar = Calendar.current
let startComp = calendar.dateComponents([.month,.day,.hour], from: startDate)
let endComp = calendar.dateComponents([.month,.day,.hour], from: endDate)
let startMonth = startComp.month!
let startDay = startComp.day!
let startHour = startComp.hour!
let endHour = endComp.hour!
dateFormatter.dateFormat = "a"
let endTime = dateFormatter.string(from: endDate)
dateFormatter.dateFormat = "E"
let startDayString = dateFormatter.string(from: startDate)
return "\(startDayString) \(startMonth)/\(startDay) \(startHour)-\(endHour) \(endTime)"
}
toDate(start: "2018-04-20 09:00:00 -0800", end: "2018-04-20 12:00:00 -0800")
Output: Fri 4/20 9-12 PM
You should read more on DateFormatter and experiment with it on your own.
https://www.zerotoappstore.com/get-year-month-day-from-date-swift.html
Var idate =res.results[r].date
date is coming from solr
The above line output is in the format
Mon Apr 22 14:49:00 2019
I have tried code but I am getting today's date I want the date which is coming from solr below is the code
Var idate2=new Date(idate)//idate I am passing which is coming from solr.....
Var n=idate2.Tolocaledatestring();
Console.log(n);
Output I am getting is 5/5/2019 but I want 22/5/2019.
Thanks
you can use this code for convert your date:
var date = new Date('Mon Apr 22 14:49:00 2019');
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
var result = day + '/' + month + '/' + year; // output is 22/3/2019
I'm trying to make a function in order to find & match the date of day in a array.
But for a weird reason, if two dates are matching, my function never find the match.
So..., if I change my date by an other string (ex : "foo" match with "foo"), it's work.
Here my code, and then the log return. Have you an idea why my script can't match two equal dates ?
Thank you !
function hideBeforeToday(values, value)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.setActiveSheet(ss.getSheetByName(roadmapSS))
var range = sheet.getRange(4, 11, 1, sheet.getLastColumn())
var values = range.getValues();
Logger.log(values);
var value = moment().set({hour:0,minute:0,second:0,millisecond:0}).utc().toDate();
Logger.log("date", value);
for(var i = 0; i < values.length; i++) {
if(values[i].indexOf(value) > -1) {
Logger.log("data found");
}
}
}
[18-01-11 13:49:33:065 CET] Logger.log([arrayValues, [[[Wed Jan 10 00:00:00 GMT+01:00 2018, Thu Jan 11 00:00:00 GMT+01:00 2018]]]]) [0 secondes]
[18-01-11 13:49:33:067 CET] Logger.log([dateOfDay, [Thu Jan 11 00:00:00 GMT+01:00 2018]]) [0 secondes]
[18-01-11 13:49:33:070 CET] Script exécuté [durée totale d'exécution : 0,535 secondes]
Look at this example:
var date1 = new Date("Thu Jan 11 00:00:00 GMT+01:00 2018");
var dates = [date1];
console.log(date1); // prints 2018-01-10T23:00:00.000Z
console.log(dates.indexOf(date1)); // prints 0
While this:
var date1 = new Date("Thu Jan 11 00:00:00 GMT+01:00 2018");
var dates = [new Date("Thu Jan 11 00:00:00 GMT+01:00 2018")];
console.log(date1); // prints 2018-01-10T23:00:00.000Z
console.log(dates.indexOf(date1)); // prints -1
I don't know what data you have in the spreadsheet, if it is a string or a Date object, but try converting both to the same type before comparing. Check their types and perhaps use the toISOString() function?
This question already has answers here:
Y returns 2012 while y returns 2011 in SimpleDateFormat
(5 answers)
Closed 5 years ago.
In Google App Script consider the following date formatting code
function testDateFormatter(){
// Sun Dec 31 2017 20:02:06
var date = new Date(1514746926811)
var dateString = Utilities.formatDate(date, "CET", "YYYY-MM-dd");
Logger.log("The date is : " + date + ", after formatting it is " + dateString)
}
The result is:
//
// The date is : Sun Dec 31 2017 20:02:06 GMT+0100 (CET), after formatting it is 2018-12-31
//
note 2018 instead of 2017 !!!!
Why GAS added the whole year to the date?
With other sample dates it works fine i.e.:
var date = new Date(1511377747255)
var dateString = Utilities.formatDate(date, "CET", "YYYY-MM-dd");
Logger.log("The date is : " + date + ", after formatting it is " + dateString)
//
// Logger: The date is : Wed Nov 22 2017 20:09:07 GMT+0100 (CET), after formatting it is 2017-11-22
//
I don't see the problem:
function myFunction() {
var dt=new Date(1514746926811);
var dts=Utilities.formatDate(dt, Session.getScriptTimeZone(), "MM/dd/yyyy HH:mm:ss")//not YYYY
Logger.log('dt=%s dts=%s',dt,dts);
}
Logger Output is:
[17-12-22 15:17:07:058 MST] dt=Sun Dec 31 12:02:06 GMT-07:00 2017 dts=12/31/2017 12:02:06
this is my jpql
#NamedQuery(name = "Subscribe.countByDate", query = "SELECT COUNT (s.idSubscribe) FROM Subscribe s WHERE s.dateInscription BETWEEN :dateS AND :dateF"),
this is my facade :
public Number subSexeDate(String v, Date dated, Date datef) {
Query query = em.createNamedQuery("Subscribe.countByDate");
//query.setParameter("sexe", v);
query.setParameter("dateS", dated, TemporalType.DATE);
query.setParameter("dateF", datef, TemporalType.DATE);
return (Number) query.getSingleResult();
}
this is my controller
public List<Number> subSexeDate() {
sexe();
Date d1= new Date(2008-01-07);
Date d2= new Date(2010-01-01);
List<Number> nb = new ArrayList<Number>();
for (String var : sexe()) {
nb.add(ejbFacade.subSexeDate("homme", d1, d2));
}
return nb;
}
the result is: [0, 0]
the real problem
Date d1 = new Date(2007-01-01); long x = d1.getTime(); long y = System.currentTimeMillis(); Date d2 = new Date(); d2.setTime(y); d1.setTime(x); List<Number> nb = new ArrayList<Number>(); for (String var : sexe()) { nb.add(ejbFacade.subSexeDate(var, d1, d2)); System.out.println(d1.toString()+"date2"+d2);}
but résult of system.out : Infos: Thu Jan 01 01:00:02 CET 1970date2Sun May 26 11:55:31 CEST 2013 –
I imagine the issue has to do with the way you are constructing your Date objects.
You are writing this:
Date d1= new Date(2008-01-07);
Which is the same as this:
long x = 2008 - 1 - 7;
Date d1 = new Date(x); // or new Date(2000L);
Which I suspect is not what you wanted. Use a DateFormat and parse your date string instead.