使用时区将字符串转换为日期

时间:2016-10-25 11:07:22

标签: ios swift swift3 nsdateformatter

我有日期字符串2017-01-03T10:45:00.000+02:00,我需要将其转移到这样的内容2017-01-03 10:45:00 +0200

 let formatter = DateFormatter()
 formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
 // this formatter returning 2017-01-03 08:45:00 +0000 but I need 
 // 2017-01-03 10:45:00 +0200

感谢您的帮助!

4 个答案:

答案 0 :(得分:2)

试试这个,

Swift 3.0

function GetIntersection(dirStart, dirEnd, p1, p2) {
   var s1_x = dirEnd.x - dirStart.x;
   var s1_y = dirEnd.z - dirStart.z;
   var s2_x = p2.x - p1.x;
   var s2_y = p2.z - p1.z;
   var div = (-s2_x * s1_y) + (s1_x * s2_y);

   if (div == 0) 
     return new Vector(0,0);

   var s = (-s1_y * (dirStart.x - p1.x) + s1_x * (dirStart.z - p1.z)) / div;
   var t = ( s2_x * (dirStart.z - p1.z) - s2_y * (dirStart.x - p1.x)) / div;

   if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
      //and (Vector(dirStart.x + (t * s1_x), 0, dirStart.z + (t * s1_y)) or nil) then
      var v = new Vector(
        dirStart.x + (t * s1_x),
        dirStart.z + (t * s1_y));
      return v;
   }
   return new Vector(0,0);
}

<强>结果:

字符串日期:可选(2017-01-03 08:45:00 +0000)

String From Date:2017-01-03 10:45:00 +0200

答案 1 :(得分:1)

这个对我有用,希望对你有帮助

 let dateString = "2017-01-03 08:45:00 +0000"

// create dateFormatter with UTC time format
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss xxxx"
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let date = dateFormatter.date(from: dateString)// create   date from string
print("Date1 : \(date)")
// change to a readable time format and change to local time zone
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss xxxx'"
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 7200) as TimeZone!
print("Date2 : \(dateFormatter.string(from: date!))")   

答案 2 :(得分:0)

如果您想将String转换为Date,请尝试以下代码并告诉我,

let dateString = "2016-10-25"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let FormatDate = dateFormatter.dateFromString(dateString)
print(FormatDate)

你可以从以下格式获得时间:

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

答案 3 :(得分:0)

试试这个:

let dateString = "2017-01-03T10:45:00.000+02:00"
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss SSSZ"
let FormatDate = dateFormatter.dateFromString(dateString)
print(FormatDate)