Wrong Value Returned After Formatting Timestamp

Wrong value returned after formatting timestamp

You've got the wrong value.

I reversed the process, starting with the date string you want, and ran it through this code:

let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .ShortStyle
let date = dateFormatter.dateFromString("Feb 20, 2016, 11:13 PM")
let timeInterval = date?.timeIntervalSince1970

In a Swift playground, timeInterval has a value of 1456031580 which is three digits shorter than the value you're using.

When I go back to your original code and use this new value:

let timestampDouble: Double = 1456031580
let timestamp = NSDate(timeIntervalSince1970: timestampDouble)
let formattedTimestamp = NSDateFormatter.localizedStringFromDate(timestamp, dateStyle: .MediumStyle, timeStyle: .ShortStyle)

We get the expected value: "Feb 20, 2016, 11:13 PM".

Of course, note that the exact time interval you get (the 1456031580 number) from the first snippet and the exact string you get out for that particular number will depend on your time zone.


Sample Image

Once you linked to Epoch Converter, I pasted your original value in here and indeed got the correct value of February something-ish. But it's important to note the bolded text.

Assuming that this timestamp is in milliseconds:

The website sees the number would give you a date 46,000 years in the future and guesses that you've actually given it milliseconds, so it makes a calculation based on that assumption.

NSDate's timeIntervalSince1970 constructor takes an argument of type NSTimeInterval, which is always a measure of seconds, not milliseconds. You need to divide your original value by 1000 to get the number of seconds, or write an NSDate constructor which expects to be initialized with the number of milliseconds since 1970 rather than the number of seconds, as the initializer you used expects.

moment js is returning wrong formatted values for an iso timestamp

You have to use .utc when passing timestamp like this:
If you do:

console.log(moment("2018-01-31").format('YYYY-MM-DD'));

It would give you the desired result but when passing timestamp like you have done now, what you should do is:

console.log(moment.utc("2018-01-31T22:55:02.907Z").format('YYYY-MM-DD'));

You can also see how this works:

console.log(moment({ years:2018, months:0, date:31, hours:22, minutes:55, seconds:02, milliseconds:907}).format('YYYY-MM-DD'));

For passing timestamp you should check the documentation again.
https://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/

This also might be a helpful link:
https://coderwall.com/p/exrbag/use-momentjs-to-parse-unix-timestamps

Formatting a timestamp to date giving wrong result

On my computer (located in PST) your code returns:

2020-03-17

Printing the hour minute and second:

timestamp = datetime.fromtimestamp(timestamp)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

Returns:

2020-03-17 12:51:58

It's possible that your local timezone is causing problems, in which case you could try localizing it to UTC:

from datetime import datetime
import pytz
dt_object = datetime.utcfromtimestamp(timestamp)
print(f"{dt_object:%Y-%m-%d %H:%M:%S}")

Which returns:

2020-03-17 19:51:58

You might want to check your local UTC offset as well:

utc_offset = datetime.fromtimestamp(timestamp) - datetime.utcfromtimestamp(timestamp)
utc_offset_hours = utc_offset.seconds/(60*60) + utc_offset.days*24
print(f"{utc_offset_hours} hours")

Groovy Timestamp conversion returning incorrect values

Because the date format should be

dd/MM/yyyy

And you get negative milliseconds because millis is calculated from the epoch which is 1st Jan 1970. Any date before that will yield negative millis value.

The actual format with timestamp would be

yyyy/MM/dd HH:mm:ss.SSS

Note caps M for month and m for minutes.

printf epochtime shows wrong values

I suppose that you want to represent the date: October 19th, 2002 00:00:00, which corresponds to the epoch timestamp that you expect: 1034985600.

In such case, you are doing it wrong. Read the manual:

Broken-down time is stored in the structure tm, which is defined in <time.h> as follows:

struct tm {
int tm_sec; /* Seconds (0-60) */
int tm_min; /* Minutes (0-59) */
int tm_hour; /* Hours (0-23) */
int tm_mday; /* Day of the month (1-31) */
int tm_mon; /* Month (0-11) */
int tm_year; /* Year - 1900 */
int tm_wday; /* Day of the week (0-6, Sunday = 0) */
int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */
int tm_isdst; /* Daylight saving time */
};

Your year should be 2002 - 1900 = 102, and your month should be 9, not 10 (months start from 0 = January).

The correct code is:

#include <stdio.h>
#include <time.h>
#include <inttypes.h>

int main(void) {
struct tm epochtime = {
.tm_mday = 19,
.tm_mon = 9,
.tm_year = 102,
.tm_hour = 0,
.tm_min = 0,
.tm_sec = 0,
.tm_isdst = -1
};

time_t epochdate = mktime(&epochtime);
if (epochdate == (time_t)(-1)) {
perror("mktime failed");
return 1;
}

printf("%" PRIuMAX "\n", (uintmax_t)epochdate);
return 0;
}

Which correctly outputs 1034985600 as you expect.

The problem with your code is most likely that mktime is not able to correctly represent the "wrong" date you provide and returns -1, which you then print as unsigned and becomes a huge nonsensical number.

SimpleDateFormat convert date incorrect return value when hour is 12

Aside from the fact you shouldn't be using Date or SimpleDateFormat any more, your error is because you are using hh instead of HH

h -> Hour in am/pm (1-12)

H -> Hour in day (0-23)

Consider using LocalDateTime in your case.

SQL query returns wrong timestamp

Because the timestamp format only goes down to seconds not milliseconds....and the update obviously doesn't take a whole second. Try putting a sleep(1) between the update and the query for update date to confirm this.

     $a = mysqli_query($sql, "SELECT `last_checked` FROM `users` WHERE `name` = '".$username."';");
$a = mysqli_fetch_row($a);

mysqli_query($sql, "UPDATE `users` SET `last_checked` = now() WHERE `name` = '".$username."';");

sleep(1); //sleep for 1 second to prove my point

$b = mysqli_query($sql, "SELECT `last_checked` FROM `users` WHERE `name` = '".$username."';");
$b = mysqli_fetch_row($b);

return json_encode($a[0]."---".$b[0]);

SImpleDateFormat return wrong value with GMT + 6.5

A few things:

  • Manipulating a timestamp by adding or subtracting offsets is never the correct way to convert for time zones, in any language. Always look for APIs that allow you to work with time zone identifiers instead. If you manipulate timestamps, you're deliberately picking a different point in time. That is not the same concept as adjusting for a local time zone.

  • There are only two time zones in the world that use +6.5. They are Asia/Yangon (in Myanmar) and Indian/Cocos (in the Cocos/Keeling Islands). You should use one of those instead.

  • Your assertion about the local time of that timestamp is incorrect.

    • 1555415100000 corresponds to the UTC time of 2019-04-16T11:45:00.000Z
    • With a +7 offset, that is 2019-04-16T18:45:00.000+07:00 (18:45, not 01:45 as you stated)
    • With a +6.5 offset, that is 2019-04-16T18:15:00.000+06:30 (18:15, not 01:15 as you stated)
  • You should consider using the java.time package, introduced with Java 8. On Android, you can use the ThreeTenABP library, a backport of the java.time API for Android.

    import java.time.*;
    import java.time.format.*;

    ...

    long time = 1555415100000L;
    Instant instant = Instant.ofEpochMilli(time);
    ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Asia/Yangon"));
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
    System.out.println(formatter.format(zonedDateTime)); //=> "18:15"
  • If you really insist on using the older date and time APIs, despite all of their very well documented problems, then you need to set the time zone of your formatter instead of manipulating the timestamp.

    import java.util.*;
    import java.text.*;

    ...

    long time = 1555415100000L;
    long date = new Date(time));
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Yangon"));
    System.out.println(sdf.format(date); //=> "18:15"

Firestore onSnapshot returning wrong timestamp format

Ended up using moment.utc() on cloud functions.

Replaced const createdAt = FieldValue.serverTimestamp() with const createdAt = moment.utc().valueOf()

After that createdAt field returns same value on both cloud functions & frontend fetch, because its stores timestamp as number instead of timestamp in the firestore.



Related Topics



Leave a reply



Submit