我有两个字符串,date和time。 date字符串的日期格式为“ MM-dd-yyyy”,时间格式为“ hh:mm a”,我想从中创建一个10位的时间戳。我做了以下工作,但与此同时遇到了问题。任何帮助表示赞赏。
let idate = (userInstance.userData?.Date!)! + "T" + (userInstance.userData?.Time!)! + "+0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let date = dateFormatter.date(from: idate)!
print(date)
let timestamp = Int(date.timeIntervalSince1970)
print(timestamp)
答案 0 :(得分:1)
您不能将包含AM / PM时间的日期强制设置为ISO8601。ISO8601日期始终以24小时模式表示。
除了您的年,月和日订单不符合ISO 8601。
指定适当的日期格式 using System;
using Xamarin.Forms;
using SlideOverKit.MoreSample;
using SlideOverKit.MoreSample.iOS;
using Xamarin.Forms.Platform.iOS;
using menutest.iOS;
using UIKit;
using CoreGraphics;
[assembly: ExportRenderer (typeof(MainPage), typeof(PageImpInterfaceRendereiOS))]
namespace menutest.iOS
{
// As your page cannot inherit from MenuContainerPage,
// You must create a renderer page, copy these codes and rename.
public class PageImpInterfaceRendereiOS : PageRenderer, ISlideOverKitPageRendereriOS
{
public Action<bool> ViewDidAppearEvent { get; set; }
public Action<VisualElementChangedEventArgs> OnElementChangedEvent { get; set; }
public Action ViewDidLayoutSubviewsEvent { get; set; }
public Action<bool> ViewDidDisappearEvent { get; set; }
public Action<CGSize, IUIViewControllerTransitionCoordinator> ViewWillTransitionToSizeEvent { get; set; }
public PageImpInterfaceRendereiOS ()
{
new SlideOverKitiOSHandler ().Init (this);
}
protected override void OnElementChanged (VisualElementChangedEventArgs e)
{
base.OnElementChanged (e);
if (OnElementChangedEvent != null)
OnElementChangedEvent (e);
}
public override void ViewDidLayoutSubviews ()
{
base.ViewDidLayoutSubviews ();
if (ViewDidLayoutSubviewsEvent != null)
ViewDidLayoutSubviewsEvent ();
}
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
if (ViewDidAppearEvent != null)
ViewDidAppearEvent (animated);
}
public override void ViewDidDisappear (bool animated)
{
base.ViewDidDisappear (animated);
if (ViewDidDisappearEvent != null)
ViewDidDisappearEvent (animated);
}
public override void ViewWillTransitionToSize (CGSize toSize, IUIViewControllerTransitionCoordinator coordinator)
{
base.ViewWillTransitionToSize (toSize, coordinator);
if (ViewWillTransitionToSizeEvent != null)
ViewWillTransitionToSizeEvent (toSize, coordinator);
}
}
}
MM-dd-yyyyhh:mm aZ
答案 1 :(得分:0)
您在这里坠毁:
let date = dateFormatter.date(from: idate)!
那是因为您声称idate
是这种格式的字符串:
"yyyy-MM-dd'T'HH:mm:ssZ"
但不是。从字符串转换为日期时,格式字符串必须完全与字符串格式匹配。
然后,您可以提供其他格式,并将日期转换为新的字符串。