Swift:将Normal String转换为YYYY-MM-DD类型String?

时间:2016-12-28 06:22:04

标签: ios swift

我需要将一个简单的字符串转换为DateFormatter字符串,以便我可以将它传递给NSDateFormatter.dateFromString.的参数 我有一个字符串

let a = "20160114"

我想将其转换为"2016-01-14" 怎么样?

5 个答案:

答案 0 :(得分:4)

仅用于将字符串转换为给定格式 你可以使用插入快速的快照

var a = "20160114"

a.insert("-", atIndex: a.startIndex.advancedBy(4))
a.insert("-", atIndex: a.startIndex.advancedBy(4+1+2))

print(a)

print:" 2016-01-14"

答案 1 :(得分:4)

    let dateString = "20160114"
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyyMMdd"

    let dateObj = dateFormatter.dateFromString(dateString)

    dateFormatter.dateFormat = "yyyy-MM-dd"
    print("Dateobj: \(dateFormatter.stringFromDate(dateObj!))")

答案 2 :(得分:2)

let dateformattor = NSDateFormatter()
dateformattor.dateFormat = "yyyyMMdd"
dateformattor.timeZone = NSTimeZone.localTimeZone()
//  here just pass your string that you want to convert into date.
let dt = "20160114" 
let dt1 = dateformattor.dateFromString(dt as String)
dateformattor.dateFormat = "yyyy-MM-dd"
dateformattor.timeZone = NSTimeZone.localTimeZone()
print("Time :",dateformattor.stringFromDate(dt1!))

输出:

Time : 2016-01-14

答案 3 :(得分:0)

这在处理日期和时间时可能不适用,但如果您只需要插入破折号(格式保证相同),这是一个更简单的解决方案

var str = "20160112"
str.characters.insert("-", at: str.index(str.startIndex, offsetBy: 6))
str.characters.insert("-", at: str.index(str.startIndex, offsetBy: 4))
print(str) // outputs "2016-01-12"

答案 4 :(得分:0)

    edtEnterAmount.setOnFocusChangeListener(this);
    InputFilter filter = new InputFilter() {
        final int maxDigitsBeforeDecimalPoint=8;
        final int maxDigitsAfterDecimalPoint=2;

        @Override
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            StringBuilder builder = new StringBuilder(dest);
            builder.replace(dstart, dend, source
                    .subSequence(start, end).toString());
            if (!builder.toString().matches(
                    "(([1-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?"

            )) {
                if(source.length()==0)
                    return dest.subSequence(dstart, dend);
                return "";
            }

            return null;

        }
    };

    edtEnterAmount.setFilters(new InputFilter[] { filter });