2016-04-14 56 views
0

日期转换所以在我的项目来自美国用户设定的一段时间说这是上午10:30 现在当一个人的一些其他国家看到时间的话,应该根据自己的时区。如何根据时区

对于美国实例是早上5:30现在 和印度是下午6:30,因此,如果5小时的人在印度之后看到的是那么这个人应该看到下午6:30该职位

+0

时间在发送到服务器之前应该转换为UTC,以便时间可以通过本地时区信息进行转换。 – zcui93

回答

0

我创建了下面的函数来解决这个问题。 它是如何工作的:假设这是您当地时间转换为GMT零时 - 2016-04-14 21:00:00 +0000

当我使用以下函数将其转换时,我在新德里印度,格林尼治标准时间+ 05:30,那么我会在凌晨2:30得到时间。

+(NSString*)getLocalTimeFromGMTzero : (NSString*)GMTzerioTimeString { 

    NSDateFormatter *df = [NSDateFormatter new]; 
    [df setDateFormat:@"yyyy-MM-dd HH:mm"];  

    //Create the date assuming the given string is in GMT 
    df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; 
    NSDate *date = [df dateFromString:GMTzerioTimeString]; 

    //Create a date string in the local timezone 
    df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:[NSTimeZone localTimeZone].secondsFromGMT]; 
    NSString *localDateString = [df stringFromDate:date]; 
    NSLog(@"date = %@", localDateString); 

    return localDateString; 
} 
0

使用PHP函数gmdate()
串gmdate(字符串$格式[摘要$时间戳=时间()]) 相同,除了返回的时间是格林威治标准时间(GMT)的日期()函数。 参数格式输出日期字符串的格式。请参阅date()函数的格式选项。 timestamp可选的timestamp参数是一个整数Unix时间戳,如果未给出时间戳,则默认为当前本地时间。换句话说,它默认为time()的值。返回值返回格式化的日期字符串。如果时间戳记使用非数字值,则返回FALSE并发出E_WARNING级别错误。在时间戳 中添加间隔。 防爆如果GMT区是5说然后添加以下功能时间戳+ 5 * 60 * 60

+0

OP仅提及客户端(iOS和Swift标签),因此最好从客户端角度解释问题。 – werediver

0

使用:

class func getDateWithFormat(format: String) -> NSDate { 
    var dateFormatter: NSDateFormatter = NSDateFormatter() 
    dateFormatter.timeZone = NSTimeZone.localTimeZone() 
    dateFormatter.dateFormat = format 
    var newDate: NSDate = dateFormatter.dateFromString(dateFormatter.stringFromDate(NSDate())) 
    return newDate 
} 

例如:VAR todaysDate:的NSDate = NSDate.getDateWithFormat(“DD:MM: yyyy hh:mm:ss a“)

+1

最好参考日期和时间格式的一些广泛使用的标准,如ISO 8601(见[wiki](https://en.wikipedia.org/wiki/ISO_8601)或此[W3C页面](https:// www.w3.org/TR/NOTE-datetime))。 – werediver

+0

所以它应该如何工作 你可以解释一下 你有没有尝试过吗? –

+0

这个功能会给你带时区的时间(出现在手机设置中)和提供的格式。 –