Date formatting not working in Swift 3 - nsdateformatter

I'm having a problem with NSDate in a function. Essentially, the formatting is not working, and I need another set of eyes to see what I'm doing wrong.
Code:
#IBOutlet weak var dateField: NSTextField!
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd yyyy"
let currentDate = NSDate()
convertedDateString = dateFormatter.string(from:currentDate as Date)
dateField.stringValue = convertedDateString as String
print("convertedDate: ", convertedDateString)
print("dateField.stringValue: ", dateField.stringValue)
Result:
convertedDate: July 25 2016
dateField.stringValue: 7/25/16

Date().toString() // convert date to string with userdefined format.
extension Date {
func toString() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd yyyy"
return dateFormatter.string(from: self)
}
}

Extension for getting string against date formats
extension Date {
func toString(format: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
Date().toString(format:"H:mm")

This is what i try on the playground and it works.
import Foundation
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM dd yyyy"
let currentDate = NSDate()
let convertedDateString = dateFormatter.stringFromDate(currentDate)
var dateField:NSTextField = NSTextField()
dateField.stringValue = convertedDateString as String
print(convertedDateString) //July 25 2016
print(dateField.stringValue) //July 25 2016
The only different was that i change to NSDateFormatter and instead of dateFormatter.string i have dateFormatter.stringFromDate.
Did you accidentally set some value in the storyboard or xib that you have the NSTextField?

The issue i had was not deleting the App from my phone before re installing and testing. The code was working in the simulator but not the phone. Hope this helps

Related

Date formatting in Karate

I have the the below date returned from the SQL query in Karate feature file:
2020-01-31 00:00:00.0
I need to convert it to: 31-JAN-20 format. I have tried the below:
* def effectiveDt =
"""
function(s) {
var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
var sdf = new SimpleDateFormat("dd-mon-yy");
return return sdf.format(s)
}
"""
but its not working for me.
but the below worked and returns 31-00-19, but I want 31-JAN-20 format
var sdf = new SimpleDateFormat("dd-mm-yy");
Any help would be appreciated!
Here is an example that worked for me:
* def getSubtractedYear =
"""
function(s) {
var DateTimeFormatter = Java.type("java.time.format.DateTimeFormatter");
var LocalDate = Java.type("java.time.LocalDate");
var ChronoUnit = Java.type("java.time.temporal.ChronoUnit");
var dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy");
try {
var adj = LocalDate.parse('02/02/2020', dtf).minusMonths(12);
return dtf.format(adj);
} catch(e) {
karate.log('*** date parse error: ', s);
}
}
"""
And call like:
* string subtracted = call getSubtractedYear aDate

How to get the sunrise/ sunset time for remote location in their timezone, not device timezone when using open weather api, in Objective C?

I am getting the sunrise/sunset time but it is in the timezone that my device is using. For example, I am in New York, when I look up cities that are in EST, it returns the sunrise/sunset time in the right timezone. But if I look up Dubai, the hours are off. The sunset time returned for Dubai is 10:57PM. Which is the time in New York(EST) when the sun sets in Dubai.
Here is my OpenWeatherAPI response-
base = stations;
clouds = {
all = 20;
};
cod = 200;
coord = {
lat = "25.27";
lon = "55.3";
};
dt = 1565620936;
id = 292223;
main = {
humidity = 71;
pressure = 995;
temp = 36;
"temp_max" = 36;
"temp_min" = 36;
};
name = Dubai;
sys = {
country = AE;
id = 7537;
message = "0.0067";
sunrise = 1565574654;
sunset = 1565621827;
type = 1;
};
timezone = 14400;
visibility = 7000;
weather = (
{
description = "few clouds";
icon = 02d;
id = 801;
main = Clouds;
}
);
wind = {
deg = 340;
speed = "4.6";
};
How do I get the sunrise/sunset time in the remote time zone that I am querying in Objective-C?
I figured it out, this is how you do it-
You use the timezone field returned in the API response and set it as the offset.
double offset = [json[#"timezone"]doubleValue]; //getting timezone offset
double sunriseTimestampval = [json[#"sys"][#"sunrise"]doubleValue];
NSTimeInterval sunriseTimestamp = (NSTimeInterval)sunriseTimestampval;
NSDate* sunriseDate = [NSDate dateWithTimeIntervalSince1970:sunriseTimestamp];
NSDateFormatter *sunriseDateFormatter = [[NSDateFormatter alloc] init];
[sunriseDateFormatter setDateFormat:#"hh:mm"];
[sunriseDateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:offset]];//->Converting to remote timezone
NSString *sunriseTime = [sunriseDateFormatter stringFromDate:sunriseDate];

Got wrong date when converting string date retrieved from the api

I'm calling an API to get some dates, but the API returns the date in string format so I'm using new Date() to convert it to date format, the problem is that after the conversion I'm getting a wrong date
For example new Date("2019-04-19") is returning Thu Apr 18 19:00:00 GMT-05:00 2019
this is my code
function HebrewCalAPI(fechas)
{
var response = UrlFetchApp.fetch("https://www.hebcal.com/hebcal/?v=1&cfg=json&maj=on&min=on&mod=on&nx=on&year=now&month=x&ss=on&mf=on&c=on&geo=geoname&geonameid=3530597&m=50&s=on");
var data = JSON.parse(response.getContentText());
var arrayEmpiezan = []
for(var i in fechas)
{
for(var i2 in data.items)
{
if(data.items[i2].title == fechas[i])
{
arrayEmpiezan.push(new Date(data.items[i2].date));
}
}
}
return arrayEmpiezan
}
var fiestasEmpiezan = ["Erev Pesach","Pesach VI (CH''M)","Erev Shavuot","Erev Rosh Hashana","Erev Yom Kippur","Erev Sukkot","Sukkot VII (Hoshana Raba)"]
var fiestasAcaban = ["Pesach II", "Pesach VIII","Shavuot II","Rosh Hashana II","Yom Kippur","Sukkot II","Simchat Torah"]
var FiestaEmpieza = date
var FiestaAcaba = date
FiestaEmpieza = HebrewCalAPI(fiestasEmpiezan)
FiestaAcaba = HebrewCalAPI(fiestasAcaban)
Any help please ?

Binary operator '-' cannot be applied to two (NSDate?) operators

Trying to get a total amount of time from a start time and end time.
I have the DateFormatter correct as in Extension.swift below but I am getting confused on the way to calculate bottomtime - starttime.
Any help is appreciated. Thanks
Extension.swift
extension NSDate{
var bottomtimestringValue: String{
return self.toString()
}
func tobottomtimeString() -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MMM-dd"
let str = formatter.stringFromDate(self)
return str
}
}
extension String{
var bottomtimedateValue: NSDate?{
return self.toDate()
}
func tobottomtimeDate() -> NSDate? {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MMM-dd"
if let date = formatter.dateFromString(self) {
return date
}else{
// if format failed, Put some code here
return nil // an example
}
}
}
Adddivelogviewcontroller.swift
var a = (textFieldStartTime.text.starttimedateValue)
var b = (textFieldEndTime.text.endtimedateValue)
var sum = b - a
textFieldBottomTime.text = "\(sum)"
That's correct-- the - operator is not defined for NSDate?, so you can't find the difference that way. Since a and b are both NSDate?, you could find the difference like this:
if let dateA = a, dateB = b {
let difference = dateA.timeIntervalSinceReferenceDate - dateB.timeIntervalSinceReferenceDate
}
Here, difference's type will be NSTimeInterval?.
Or if you prefer, you could add a definition of - for NSDate?, which might look like this:
func -(lhs:NSDate?, rhs:NSDate?) -> NSTimeInterval? {
if let left=lhs, right=rhs {
return left.timeIntervalSinceReferenceDate - right.timeIntervalSinceReferenceDate
} else {
return nil
}
}
Add that and you can use - above.
OK, not really sure if thats working or not but i get no errors. What I need this to do calculate after the end time picker OK botton is pressed
func OK3ButtonTapped(sender: UIBarButtonItem) {
self.textFieldEndTime.endEditing(true)
self.textFieldEndTime.text = endtimePickerView.date.endtimestringValue
var a = (textFieldStartTime.text.starttimedateValue)
var b = (textFieldEndTime.text.endtimedateValue)
var difference: String = ""
if let dateA = a, dateB = b {
let difference = dateA.timeIntervalSinceReferenceDate - dateB.timeIntervalSinceReferenceDate
}
textFieldBottomTime.text = "\(difference)"
}

Hazelcast SqlPredicate on Date object

i'm trying to build a SqlPredicate with Hazelcast that should filter by a date.
The exception i get is the following:
java.lang.RuntimeException: Unable to parse date from value: '2013-06-21 03:15:44.000' !
Valid formats are: 'EEE MMM dd HH:mm:ss zzz yyyy', 'yyyy-MM-dd hh:mm:ss.SSS' and 'yyyy-mm-dd'.
The strange thing is that my date exacly match the second "valid" pattern.
What should i do?
Thanks in advance...
I'm looking at the hazelcast source code, version 2.5, in package com.hazelcast.query, and it seems that date-related expressions used in a Predicate need to be in the format according to their type:
java.util.Timestamp - "yyyy-MM-dd hh:mm:ss.SSS"
java.sql.Date - "yyyy-mm-dd"
java.util.Date - "EEE MMM dd HH:mm:ss zzz yyyy"
If you could easily use java.util.Timestamp, you can use the date expression in the format you have it.
Alternatively if you are using java.util.Date then can you try the same date in the format "EEE MMM dd HH:mm:ss zzz yyyy"?
Hope this helps.
Relevant hazelcast source code from Predicates.java pasted below:
} else if (type instanceof Timestamp) {
if (value instanceof Date) { // one of java.util.Date or java.sql.Date
result = value;
} else {
result = DateHelper.parseTimeStamp(valueString);
}
} else if (type instanceof java.sql.Date) {
if (value instanceof Date) { // one of java.util.Date or java.sql.Timestamp
result = value;
} else {
result = DateHelper.parseSqlDate(valueString);
}
} else if (type instanceof Date) {
if (value instanceof Date) { // one of java.sql.Date or java.sql.Timestamp
result = value;
} else {
result = DateHelper.parseDate(valueString);
}
And from DateHelper.java
static final String timestampFormat = "yyyy-MM-dd hh:mm:ss.SSS";
static final String dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy";
static final String sqlDateFormat = "yyyy-mm-dd";