Specific String format to NSDate - string

I have this String 2015-02-17T08:53:22.9170000+00:00 and I want to converted to NSdate.
The prefered format to print is hh:mm:ss-dd-mm-yyyy.

Try this one
let string = "2015-02-17T08:53:22.9170000+00:00"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSz"
if let date = formatter.dateFromString(string) {
//Now you can format what ever you want, like
formatter.dateFormat = "hh:mm:ss-dd-mm-yyyy"
print(formatter.stringFromDate(date))
}

Related

Rust Chrono parse date String, ParseError(NotEnough) and ParseError(TooShort)

How to convert a String to a chrono::DateTime or chrono::NaiveDateTime
And what does the ParseError(NotEnough) or ParseError(TooShort) mean?
When converting a String into a Chrono object you have to know what parts the input format of the string has.
The parts are: Date, Time, TimeZone
Examples:
"2020-04-12" => Date = NaiveDate
"22:10" => Time = NaiveTime
"2020-04-12 22:10:57" => Date + Time = NaiveDateTime
"2020-04-12 22:10:57+02:00" => Date + Time + TimeZone = DateTime<Tz>
The ParseError(NotEnough) shows up when there is not enough information to fill out the whole object. For example the date, time or timezone is missing.
When the formats doesn't match the string you get a ParseError(TooShort) or ParseError(Invalid) error.
Specification for string format e.g. "%Y-%m-%d %H:%M:%S": https://docs.rs/chrono/latest/chrono/format/strftime/index.html
RFC2822 = Date + Time + TimeZone
To convert a RFC2822 string use the parse_from_rfc2822(..) function.
let date_str = "Tue, 1 Jul 2003 10:52:37 +0200";
let datetime = DateTime::parse_from_rfc2822(date_str).unwrap();
RFC3339 = Date + Time + TimeZone
To convert a RFC3339 or ISO 8601 string use the parse_from_rfc3339(..) function.
let date_str = "2020-04-12T22:10:57+02:00";
// convert the string into DateTime<FixedOffset>
let datetime = DateTime::parse_from_rfc3339(date_str).unwrap();
// convert the string into DateTime<Utc> or other timezone
let datetime_utc = datetime.with_timezone(&Utc);
Date + Time + Timezone (other or non-standard)
To convert other DateTime strings use the parse_from_str(..) function.
let date_str = "2020-04-12 22:10:57 +02:00";
let datetime = DateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S %z").unwrap();
Date + Time
When you do not have a TimeZone you need to use NaiveDateTime. This object does not store a timezone:
let date_str = "2020-04-12 22:10:57";
let naive_datetime = NaiveDateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S").unwrap();
Date
If we were parsing a date (with no time) we can store it in a NaiveDate. This object does not store time or a timezone:
let date_str = "2020-04-12";
let naive_date = NaiveDate::parse_from_str(date_str, "%Y-%m-%d").unwrap();
Time
If we were parsing a time (with no date) we can store it in a NaiveTime. This object does not store a date or a timezone:
let time_str = "22:10:57";
let naive_time = NaiveTime::parse_from_str(time_str, "%H:%M:%S").unwrap();
Add Date, Time and/or Timezone
If we have some string and want to add more information we can change the type. But you have to provide this information yourself.
let date_str = "2020-04-12";
// From string to a NaiveDate
let naive_date = NaiveDate::parse_from_str(date_str, "%Y-%m-%d").unwrap();
// Add some default time to convert it into a NaiveDateTime
let naive_datetime: NaiveDateTime = naive_date.and_hms(0,0,0);
// Add a timezone to the object to convert it into a DateTime<UTC>
let datetime_utc = DateTime::<Utc>::from_utc(naive_datetime, Utc);
Example code playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d2b83b3980a5f8fb2e798271766b4541

swift how to convert string to date fraction seconds

I have a string want to convert to date, but below code,
that str
print out show Optional(2016-04-25 17:00:16 +0000)
I want to know how to show exact what it is like Optional(2016-04-26T03:00:16.047)
var str = "2016-04-26T03:00:16.047"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString(str)
print(date) //Optional(2016-04-25 17:00:16 +0000)

How to convert NSString to Character in Swift?

I want to convert NSString to Character in Swift.
I am getting a String from NSTextField, where I input a single character (Example "#"), I need this in Character type.
Use Character class
var chars = [Character](str)
this should be as simple as let characterFromString = Character(textField.text).
NSString is automatically bridged to Swift's String, and the Character class has an init which accepts a single character String; see the documentation here.
This requires that the input string contain a single grapheme cluster (i.e. a single character) and so you might want to validate your input before casting. A slightly more verbose version of the above would be:
let text = textField.text as String
if countElements(text) == 1 {
let character = Character(text)
// do what you want
} else {
// bad input :-(
}
The stringValue of NSTextField actually returns a Swift string and not NSString:
let str = myTextField.stringValue // str is a String
You get the first element with
let ch = str[str.startIndex] // ch is a Character
A NSString would have to be converted to a Swift string first:
let nsString : NSString = "#"
let str = String(nsString)
let ch = str[str.startIndex]

String interpolation in Swift

A function in swift takes any numeric type in Swift (Int, Double, Float, UInt, etc).
the function converts the number to a string
the function signature is as follows :
func swiftNumbers <T : NumericType> (number : T) -> String {
//body
}
NumericType is a custom protocol that has been added to numeric types in Swift.
inside the body of the function, the number should be converted to a string:
I use the following
var stringFromNumber = "\(number)"
which is not so elegant, PLUS : if the absolute value of the number is strictly inferior to 0.0001 it gives this:
"\(0.000099)" //"9.9e-05"
or if the number is a big number :
"\(999999999999999999.9999)" //"1e+18"
is there a way to work around this string interpolation limitation? (without using Objective-C)
P.S :
NumberFormater doesn't work either
import Foundation
let number : NSNumber = 9_999_999_999_999_997
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 20
formatter.minimumIntegerDigits = 20
formatter.minimumSignificantDigits = 40
formatter.string(from: number) // "9999999999999996.000000000000000000000000"
let stringFromNumber = String(format: "%20.20f", number) // "0.00000000000000000000"
Swift String Interpolation
1) Adding different types to a string
2) Means the string is created from a mix of constants, variables, literals or expressions.
Example:
let length:Float = 3.14
var breadth = 10
var myString = "Area of a rectangle is length*breadth"
myString = "\(myString) i.e. = \(length)*\(breadth)"
Output:
3.14
10
Area of a rectangle is length*breadth
Area of a rectangle is length*breadth i.e. = 3.14*10
Use the Swift String initializer: String(format: <#String#>, arguments: <#[CVarArgType]#>)
For example:
let stringFromNumber = String(format: "%.2f", number)
String and Characters conforms to StringInterpolationProtocol protocol which provide more power to the strings.
StringInterpolationProtocol - "Represents the contents of a string literal with interpolations while it’s being built up."
String interpolation has been around since the earliest days of Swift, but in Swift 5.0 it’s getting a massive overhaul to make it faster and more powerful.
let name = "Ashwinee Dhakde"
print("Hello, I'm \(name)")
Using the new string interpolation system in Swift 5.0 we can extend String.StringInterpolation to add our own custom interpolations, like this:
extension String.StringInterpolation {
mutating func appendInterpolation(_ value: Date) {
let formatter = DateFormatter()
formatter.dateStyle = .full
let dateString = formatter.string(from: value)
appendLiteral(dateString)
}
}
Usage: print("Today's date is \(Date()).")
We can even provide user-defined names to use String-Interpolation, let's understand with an example.
extension String.StringInterpolation {
mutating func appendInterpolation(JSON JSONData: Data) {
guard
let JSONObject = try? JSONSerialization.jsonObject(with: JSONData, options: []),
let jsonData = try? JSONSerialization.data(withJSONObject: JSONObject, options: .prettyPrinted) else {
appendInterpolation("Invalid JSON data")
return
}
appendInterpolation("\n\(String(decoding: jsonData, as: UTF8.self))")
}
}
print("The JSON is \(JSON: jsonData)")
Whenever we want to provide "JSON" in the string interpolation statement, it will print the .prettyPrinted
Isn't it cool!!

Selecting a tuple index using a variable in Swift

That is what i am trying to do:
var i = 0
var string = "abcdef"
for value in string
{
value.[Put value of variable i here] = "a"
i++
}
How can i insert the value of i in the code?
Easiest is probably just convert it to an NSMutableString:
let string = "abcdef".mutableCopy() as NSMutableString
println( "\(string)")
for var i = 0; i < string.length; ++i {
string.replaceCharactersInRange(NSMakeRange(i, 1), withString: "a")
}
println( "\(string)")
Yes, it's a bit ugly but it works.
A much cleaner way is to use Swifts map function:
var string = "abcdef"
let result = map(string) { (c) -> Character in
"a"
}
println("\(result)") // aaaaaa
You should just be able to use the following but this doesn't compile:
map(string) { "a" }
In you comments you mention you want to split up the string on a space, you can just use this for that:
let stringWithSpace = "abcdef 012345"
let splitString = stringWithSpace.componentsSeparatedByString(" ")
println("\(splitString[0])") // abcdef
println("\(splitString[1])") // 012345

Resources