Using Dateformatter on a Unix Timestamp

Using DateFormatter on a Unix timestamp

You can convert unixTimestamp to date using Date(timeIntervalSince1970:).

let unixTimestamp = 1480134638.0
let date = Date(timeIntervalSince1970: unixTimestamp)

If you want to display date in string with specific formate than you can use DateFormatter like this way.

let date = Date(timeIntervalSince1970: unixtimeInterval)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" //Specify your format that you want
let strDate = dateFormatter.string(from: date)

Swift convert unix time to date and time

To get the date to show as the current time zone I used the following.

if let timeResult = (jsonResult["dt"] as? Double) {
let date = NSDate(timeIntervalSince1970: timeResult)
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle //Set time style
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle //Set date style
dateFormatter.timeZone = NSTimeZone()
let localDate = dateFormatter.stringFromDate(date)
}

Swift 3.0 Version

if let timeResult = (jsonResult["dt"] as? Double) {
let date = Date(timeIntervalSince1970: timeResult)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
dateFormatter.timeZone = self.timeZone
let localDate = dateFormatter.string(from: date)
}

Swift 5

if let timeResult = (jsonResult["dt"] as? Double) {
let date = Date(timeIntervalSince1970: timeResult)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
dateFormatter.timeZone = .current
let localDate = dateFormatter.string(from: date)
}

Getting date and time from unix timestamp

Usually unix timestamps are in milliseconds, but Date uses seconds. You might need to divide your timestamp by 1000.

Convert Unix timestamp to date object swift 5

Cast the unix time stamp to a Double and call Date(timeIntervalSince1970:).

(Note: That converts the time stamp to a date. But how it is represented visibly, in the console or any other form of string output, is a completely different matter.)

Swift convert unix time to date and time gives incorrect year

Divide timestamp by 1000, because Date uses seconds and the timestamp was generated with milliseconds and use TimeInterval instead of Double.

    let dateVal = TimeInterval(1598859638000) / 1000.0


let date = Date(timeIntervalSince1970: TimeInterval(dateVal))
print(date, "date", date.timeIntervalSince1970)


let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.init(abbreviation: "en")
dateFormatter.locale = Locale.init(identifier: "en")
dateFormatter.dateFormat = "E MMM d yyyy"
let outputDate = dateFormatter.string(from: date)
print(outputDate) // Mon Aug 31 2020

I guess your timestamp is generetd in a Java / Kotlin Applicatin. In java,
(new Date(1598859638000l)) yields Mon Aug 31 2020.

amcharts4 Format date from unix timestamp

There are couple of things wrong with your code.

First, amCharts expects dates to be sorted in ascending order. Your data is currently out of order, causing the chart to look weird.

Second, you don't need to format your data in string format. You can still use your timestamp (provided that you multiply by 1000 seconds) and use the chart's dateFormatter to parse it through the "x" code in inputDateFormatter, as documented here.

Since you're using dataSource, you can use the parseended event to manipulate your data before it is assigned to the chart like so:

chart.dataSource.events.on("parseended", function(ev) {
// parsed data is assigned to data source's `data` property
var data = ev.target.data;
data.sort(function(lhs, rhs) {
return lhs.time - rhs.time;
});
data.forEach(function(item) {
item.time *= 1000;
});
});

chart.dateFormatter.inputDateFormat = "x";

To change the dates, you have to modify your date axis' dateFormats and periodChangeDateFormats list objects and set the appropriate date format for the period(s) you want to reformat. Since your data is in minutes, you'll want to call setKey on the minutes period and adjust accordingly as documented here, for example:

dateAxis.dateFormats.setKey("minute", "MMM dd\nHH:mm");
dateAxis.periodChangeDateFormats.setKey("minute", "MMM dd\nHH:mm");

Fully updated code below:

am4core.useTheme(am4themes_animated);
var chart = am4core.create("chartdiv", am4charts.XYChart);chart.dataSource.url = "https://api.myjson.com/bins/8se3o";chart.dataSource.events.on("parseended", function(ev) { // parsed data is assigned to data source's `data` property var data = ev.target.data; data.sort(function(lhs, rhs) { return lhs.time - rhs.time; }); data.forEach(function(item) { item.time *= 1000; });});
chart.dateFormatter.inputDateFormat = "x";

var dateAxis = chart.xAxes.push(new am4charts.DateAxis());dateAxis.dateFormats.setKey("minute", "MMM dd\nHH:mm");dateAxis.periodChangeDateFormats.setKey("minute", "MMM dd\nHH:mm");
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());valueAxis.tooltip.disabled = true;
var series = chart.series.push(new am4charts.LineSeries());series.dataFields.dateX = "time";series.name = "outDiff";series.dataFields.valueY = "outDiff";series.tooltipHTML = "<span style='font-size:14px; color:#000000;'><b>{valueY.value}</b></span>";series.tooltipText = "[#000]{valueY.value}[/]";series.tooltip.background.fill = am4core.color("#FFF");series.tooltip.getStrokeFromObject = true;series.tooltip.background.strokeWidth = 3;series.tooltip.getFillFromObject = false;series.fillOpacity = 0.6;series.strokeWidth = 2;series.stacked = true;
var series2 = chart.series.push(new am4charts.LineSeries());series2.name = "inDiff";series2.dataFields.dateX = "time";series2.dataFields.valueY = "inDiff";series2.tooltipHTML = "<span style='font-size:14px; color:#000000;'><b>{valueY.value}</b></span>";series2.tooltipText = "[#000]{valueY.value}[/]";series2.tooltip.background.fill = am4core.color("#FFF");series2.tooltip.getFillFromObject = false;series2.tooltip.getStrokeFromObject = true;series2.tooltip.background.strokeWidth = 3;series2.sequencedInterpolation = true;series2.fillOpacity = 0.6;series2.stacked = true;series2.strokeWidth = 2;
chart.cursor = new am4charts.XYCursor();chart.cursor.xAxis = dateAxis;chart.scrollbarX = new am4core.Scrollbar();

chart.legend = new am4charts.Legend();chart.legend.position = "top";
body {  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";}
#chartdiv { width: 100%; height: 500px;}
<script src="https://www.amcharts.com/lib/4/core.js"></script><script src="https://www.amcharts.com/lib/4/charts.js"></script><script src="https://www.amcharts.com/lib/4/themes/animated.js"></script><div id="chartdiv"></div>

Get wrong date value after converting unix time stamp

The timestamp 1589275703283 is way too big for a "normal" UNIX timestamp. It's in milliseconds instead of seconds (which epochconverter.com is smart enough to detect; it's printing "Assuming that this timestamp is in milliseconds"). So you need to divide your timestamp by 1000:

let date = Date(timeIntervalSince1970: TimeInterval(timestamp) / 1000)

Convert Timestamp to Date with various formats Swift

As from Calendar object you can get if the date is today or yesterday.
based on that you can set String as you like.
I've created an example like you need.
below is code.

var yesterdayStr = "17-Jan-2018 10:23 AM"
var todayStr = "18-Jan-2018 10:23 AM"
var tomorrowStr = "19-Jan-2018 10:23 AM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy hh:mm a"
let yesterDaydate = dateFormatter.date(from: yesterdayStr)
let todayDate = dateFormatter.date(from: todayStr)
let tomorrowDate = dateFormatter.date(from: tomorrowStr)
let anotherDateFormatter = DateFormatter()
anotherDateFormatter.dateFormat = "hh:mm a"
if Calendar.current.isDateInYesterday(yesterDaydate!)
{
let yesterdayDisplayString = "Yesterday, " + anotherDateFormatter.string(from: yesterDaydate!)
}
if Calendar.current.isDateInToday(todayDate!) {
let todayDisplayString = "Today, " + anotherDateFormatter.string(from: todayDate!)
}
if Calendar.current.isDateInToday(tomorrowDate!) {

}
else {
let anotherDisplayString = anotherDateFormatter.string(from: tomorrowDate!)
}

and here is output,
Output of date Formatter



Related Topics



Leave a reply



Submit