Convert string to NSDate and get date, hour, Minute (swift2.3)

Source: Internet
Author: User

Main code:

Get time model, parameter format: 2016-12-12 18:11:12

Func getdatemodelwithstring (datestr:string)->datemodel? {

var model:datemodel?

Let formatter =nsdateformatter.init ()

Date gets GMT time, which differs from Beijing time by 8 hours and requires the following settings

Formatter.locale = Nslocale.currentlocale ()

Formatter.dateformat = "Yyyy-mm-dd HH:mm:ss"

Let date = formatter.datefromstring (DATESTR)

If date!=nil {

Needrealvaluemessage ("------tool.h----Datemodel")

Model = Datemodel.getmodelwithdate (date!)

}

Return model

}



Class Datemodel:nsobject {


var year:int = 0

var month:int = 0

var day:int = 0

var hour:int = 0

var minute:int = 0

var second:int = 0

Classfunc getmodelwithdate (newdate:nsdate), datemodel{

Let model = Datemodel ()

Let calendar = Nscalendar.init (Identifier:nscalendaridentifiergregorian)

Iflet year = calendar?.component (Nscalendarunit.year, fromdate:newdate) {

Model.year = Year

}

Iflet month = calendar?.component (Nscalendarunit.month, fromdate:newdate) {

Model.month = Month

}

Iflet day = calendar?.component (Nscalendarunit.day, fromdate:newdate) {

Model.day = Day

}

Iflet hour = calendar?.component (Nscalendarunit.hour, fromdate:newdate) {

Model.hour = Hour

}

Iflet minute = Calendar?.component (Nscalendarunit.minute, fromdate:newdate) {

Model.minute = Minute

}

Iflet second = calendar?.component (Nscalendarunit.second, fromdate:newdate) {

Model.second = Second

}

Return model

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.