Covert date to epoch timestamp using Javascript - javascript

I have date in MM/DD/YYYY HH:MM AM/PM format
Example 07/27/2022 10:36 AM
I want to convert it into Epoch timestamp which is 1658898360

You can use the date.getTime method to convert it to epoch:
const date = new Date("07/27/2022 10:36 AM");
console.log(date.getTime() / 1000)
Just be sure that you (or the client) is in the same timezone you are expecting (IST in this case).
Or just add GMT+5:30 to ensure this.
const date = new Date("07/27/2022 10:36 AM GMT+5:30");
console.log(date.getTime() / 1000)

The Date object in Javascript is notoriously tricky to work with, and date parsing is sadly lacking. Simply using
const dateString = "07/27/2022 10:36 AM"
const date = new Date(dateString)
might work, but not reliably.
One option is to use the date-fns library:
import { parse, getUnixTime } from 'date-fns'
const date = parse('07/27/2022 10:36 AM', 'MM/dd/yyyy hh:mm a', new Date())
const epoch = getUnixTime(date)

You can use below sample code:
function epoch (date) {
return Date.parse(date)
}
const dateToday = new Date()
const timestamp = epoch(dateToday)
console.log( timestamp )

Related

how to Convert Date into ISO Date Format in javascript

i have a date like this which i should convert them into ISO format
const date = 05/23/2022;
i need like this
2022-05-23T00:00:00Z
Note that .toISOString() always returns a timestamp in UTC, even if the moment in question is in local mode. This is done to provide consistency with the specification for native JavaScript Date .toISOString(), as outlined in the ES2015 specification.
let date = '24.05.2022 0:00:00';
let parsedDate = moment(date, 'DD.MM.YYYY H:mm:ss')
console.log(parsedDate.toISOString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
You can use String.split() to get the day, month and year for the Date in question.
We can then pass to the Date.UTC() function and then the Date() constructor. (Note: We pass monthIndex to the Date constructor, that's why we subtract 1 from the month )
To display as an ISO string, we can then use Date.toISOString()
const [month, day, year] = '05/23/2022'.split('/');
const date = new Date(Date.UTC(year, month - 1, day));
const result = date.toISOString();
console.log('Date (ISO):', result);
We can also do this easily with a Date / Time library such as luxon.
We'd use the DateTime.fromFormat() function to parse the input string, setting the timezone to 'UTC'.
To output the ISO date, we can use the DateTime.toISO() function:
const { DateTime } = luxon;
const date = DateTime.fromFormat('05/23/2022', 'MM/dd/yyyy', { zone: 'UTC'});
console.log('Date (ISO):', date.toISO())
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js" integrity="sha512-Nw0Abk+Ywwk5FzYTxtB70/xJRiCI0S2ORbXI3VBlFpKJ44LM6cW2WxIIolyKEOxOuMI90GIfXdlZRJepu7cczA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
We can also do this in moment.js, using moment.utc(), then .toISOString():
const date = moment.utc('05/23/2022', 'MM/DD/YYYY');
console.log('Date (ISO):', date.toISOString())
<script src="https://momentjs.com/downloads/moment.js"></script>

How to convert into Format 2016-10-19T08:00:00Z with momentjs

in a project we are using momentjs with date. And from backend we become the date in the following format: 2016-10-19T08:00:00Z (don't ask me why...)
Now we are setting a new date in frontend from some selectboxes. And I am trying to convert this in the same format:
const date = '25.03.2021';
const hour = '13';
const minute = '45'; // this 3 values come from value of selectboxes
const rawDate = moment(date).hour(hour).minute(minute);
// trying to convert to 2021-03-25T13:45:00Z
rawDate.format(); // output: 2021-03-25T13:45:00+00:00
rawDate.format('DD.MM.YYYY hh:mm:ss'); // output: 03.01.2022 08:00:00
rawDate.format('DD.MM.YYYY hh:mm:ss z'); // output: 03.01.2022 08:00:00 UTC
rawDate.format('DD.MM.YYYY hh:mm:ss Z'); // output: 03.01.2022 08:00:00 +00:00
rawDate.toISOString(); // output: 2022-01-03T08:00:00.000Z
I know I could probably just use format() or toISOString() and slice/replace the last bit. But I like to know is there a way without any string concat/manipulation?
You could use moment.utc() to ensure your date is in UTC, then use .format() with the format string DD-MM-YYYYTHH:mm:ss[Z].
I'd also suggest explicity defining the format you are parsing from in the moment() call, e.g. pass 'DD.MM.YYYY' as the second argument.
The reason the backend takes dates in this format is that it's a standardized way of formatting dates to make them machine-readable and consistent (ISO 8601)
const date = '25.03.2021';
const hour = '13';
const minute = '45';
// Raw date will be in the UTC timezone.
const rawDate = moment(date, 'DD.MM.YYYY').hour(hour).minute(minute).utc();
console.log(rawDate.format('DD-MM-YYYYTHH:mm:ss[Z]'));
<script src="https://momentjs.com/downloads/moment.js"></script>
You can try convert to UTC ..?
i.e. Do you intend to make use of a UTC date/time..?
const date = '2021-03-25';
const hour = '13';
const minute = '45'; // this 3 values come from value of selectboxes
const rawDate = moment(date).hour(hour).minute(minute);
const utc = moment.utc(rawDate);
console.log(rawDate.format('DD.MM.YYYY hh:mm:ss'));
console.log(utc.format()); //2021-03-25T11:45:00Z

Proper way to parse a date as UTC using date-fns

I have a log file with some timestamps
2020-12-03 08:30:00
2020-12-03 08:40:00
...
I know from the log provider's documentation that the timestamps are written in UTC (although not using ISO format)
Now I want to parse them with date-fns :
const toParse = "2020-12-03 08:40:00"
parse(toParse, 'yyyy-MM-dd HH:mm:ss', new Date()).toISOString()
And because the locale of my computer is in UTC+1 here is what I see:
> "2020-12-03T07:40:00Z"
expected:
> "2020-12-03T08:40:00Z".
Here is the hack I currently use to tell date-fns to parse as UTC :
const toParse = "2020-12-03 08:40:00"
parse(toParse + '+00', 'yyyy-MM-dd HH:mm:ss' + 'X', new Date()).toISOString()
And as expected,
> "2020-12-03T08:40:00Z".
Is there any proper way of doing this using date-fns? Looking for an equivalent to moment's moment.utc()
I don't know about "proper", but you can use zonedTimeToUtc to treat a timestamp as having any offset or timezone you like, including UTC, e.g.
// Setup
var {parse} = require('date-fns');
var {zonedTimeToUtc} = require('date-fns-tz');
// Parse an ISO 8601 timestamp recognised by date-fns
let loc = 'UTC';
let s1 = '2020-12-03 08:30:00';
let utcDate = zonedTimeToUtc(s1, loc);
// Show UTC ISO 8601 timestamp
console.log(utcDate.toISOString()); // "2020-12-03T08:30:00.000Z"
// Parse non–standard format yyyyMMdd
let s2 = '20210119';
let fIn = 'yyyyMMdd';
let d = zonedTimeToUtc(parse(s2, fIn, new Date()), loc);
console.log(d.toISOString()); // "2021-01-19T00:00:00.000Z"```
You can test it at npm.runkit.com/date-fns.
I think you are looking for parseJSON, which supports a number of formats (but does not let you specify the source format).
Converts a complete ISO date string in UTC time, the typical format for transmitting a date in JSON, to a JavaScript Date instance.
import { parseJSON } from 'date-fns';
const utcDate = parseJSON('2020-12-03 08:40:00');
// Thu Dec 03 2020 19:40:00 GMT+1100 (Australian Eastern Daylight Time)
Example of using parse and zonedTimeToUtc
it('should parse polish date', async () => {
expect.assertions(1)
const dateWithoutTime = '29 gru 2003'
const parsed = parse(dateWithoutTime, 'd LLL yyyy', new Date(), {
locale: pl,
})
const dateUTC = zonedTimeToUtc(parsed, 'UTC')
expect(dateUTC.toISOString()).toStrictEqual('2003-12-29T00:00:00.000Z')
})

date-fns | How do I format to UTC

Problem
It looks like when I use the format() function, it automatically convert the original UTC time into my timezone (UTC+8). I have been digging through their docs for hours and couldn't seem to find a way to default it to UTC time.
import { parseISO, format } from "date-fns";
const time = "2019-10-25T08:10:00Z";
const parsedTime = parseISO(time);
console.log(parsedTime); // 2019-10-25T08:10:00.000Z
const formattedTime = format(parsedTime, "yyyy-MM-dd kk:mm:ss");
console.log(formattedTime); // 2019-10-25 16:10:00 <-- 8 HOURS OFF!!
I have tried to use the package data-fns-tz and use something like
format(parsedTime, "yyyy-MM-dd kk:mm:ss", {timeZone: "UTC"});
still no luck.
Please help!
Expected Output
2019-10-25 08:10:00
Actual Output
2019-10-25 16:10:00
You were almost there. This works for me:
import { parseISO } from "date-fns";
import { format, utcToZonedTime } from "date-fns-tz";
const time = "2019-10-25T08:10:00Z";
const parsedTime = parseISO(time);
console.log(parsedTime); // 2019-10-25T08:10:00.000Z
const formatInTimeZone = (date, fmt, tz) =>
format(utcToZonedTime(date, tz),
fmt,
{ timeZone: tz });
const formattedTime = formatInTimeZone(parsedTime, "yyyy-MM-dd kk:mm:ss xxx", "UTC");
console.log(formattedTime); // 2019-10-25 08:10:00 +00:00
Behind the scenes
The date-fns[-tz] libraries stick to the built-in Date data type that carries no TZ info.
Some functions treat it as a moment-in-time, but some like format treat it more like a struct of calendaric components — year 2019, ..., day 25, hour 08, ....
Now the trouble is a Date is internally only a moment in time. Its methods provide a mapping to/from calendaric components in local time zone.
So to represent a different time zone, date-fns-tz/utcToZonedTime temporarily produces Date instances which represent the wrong moment in time — just to get its calendaric components in local time to be what we want!
And the date-fns-tz/format function's timeZone input affects only the template chars that print the time zone (XX..X, xx..x, zz..z, OO..O).
See https://github.com/marnusw/date-fns-tz/issues/36 for some discussion of this "shifting" technique (and of real use cases that motivated them)...
It's a bit low-level & risky, but the specific way I composed them above — formatInTimeZone() — is I believe a safe recipe.
I would suggest using the built-in Date util:
const date = new Date("2019-10-25T08:10:00Z");
const isoDate = date.toISOString();
console.log(`${isoDate.substring(0, 10)} ${isoDate.substring(11, 19)}`);
Outputs:
2019-10-25 08:10:00
Not a general solution for any format, but no external libraries required.
Note
The following solution will not work for all time zones, so if timezone accuracy is critical for your application you might want to try something like the answer from Beni. See this link for more info
I had the exact same question today and did some research to see if anyone has come up with anything better since this question was posed. I came across this solution which fit my needs and stylistic preference:
import { format, addMinutes } from 'date-fns';
function formatDate(date) {
return format(addMinutes(date, date.getTimezoneOffset()), 'yyyy-MM-dd HH:mm:ss');
}
Explanation
getTimezoneOffset returns the number of minutes needed to convert that date to UTC. In PST (-0800 hours) it would return 480 whereas for somebody on CST (+0800 hours) it would return -480.
I had the same problem. What I do is remove the timezone from the ISO string and then use that time with date-fns:
let time = "2019-10-25T08:10:00Z".slice(0, -1)
The above is a time with no time zone, and because there is no timezone date-fns assumes the local timezone, so when you do:
format(parseISO(time), 'h:mm a')
you get: 8:10 AM, or whatever format you prefer. You just have to be careful with the string that you are slicing. If its always the same format then it should work.
I did something like this using date/fns and native date methods
import format from 'date-fns/format';
import parseISO from 'date-fns/parseISO';
export const adjustForUTCOffset = date => {
return new Date(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
date.getUTCSeconds(),
);
};
const formatDate = (dateString) = > {
const date = parseISO(dateString);
const dateWithOffset = adjustForUTCOffset(date)
return format(dateWithOffset, 'LLL dd, yyyy HH:mm')
}
Here is how I did it
const now = new Date()
const date = format(
new Date(now.toISOString().slice(0, -1)),
'yyyy-MM-dd HH:mm:ss'
)
I just removed the Z from the ISO string. I'm not sure if it solves this issue though
solution for timestamp
format(utcToZonedTime(timestamp, 'UTC'), 'MM/dd/yyyy hh:mm a', { timeZone: 'UTC' })
I guess
To construct the date as UTC before parsing would be helpful.
import { parseISO, format } from "date-fns";
const time = "2019-10-25T08:10:00Z";
const parsedTime = parseISO(new Date(Date.UTC(time)));
const formattedTime = format(parsedTime, "yyyy-MM-dd kk:mm:ss");
like this.
try
const formatDate = new Date().toISOString().substr(0, 19).replace('T', ' ');

from unix timestamp to datetime

I have something like /Date(1370001284000+0200)/ as timestamp. I guess it is a unix date, isn't it? How can I convert this to a date like this: 31.05.2013 13:54:44
I tried THIS converter for 1370001284 and it gives the right date. So it is in seconds.
But I still get the wrong date for:
var substring = unix_timestamp.replace("/Date(", "");
substring = substring.replace("000+0200)/", "");
var date = new Date();
date.setSeconds(substring);
return date;
Note my use of t.format comes from using Moment.js, it is not part of JavaScript's standard Date prototype.
A Unix timestamp is the number of seconds since 1970-01-01 00:00:00 UTC.
The presence of the +0200 means the numeric string is not a Unix timestamp as it contains timezone adjustment information. You need to handle that separately.
If your timestamp string is in milliseconds, then you can use the milliseconds constructor and Moment.js to format the date into a string:
var t = new Date( 1370001284000 );
var formatted = moment(t).format("dd.mm.yyyy hh:MM:ss");
If your timestamp string is in seconds, then use setSeconds:
var t = new Date();
t.setSeconds( 1370001284 );
var formatted = moment(t).format("dd.mm.yyyy hh:MM:ss");
Looks like you might want the ISO format so that you can retain the timezone.
var dateTime = new Date(1370001284000);
dateTime.toISOString(); // Returns "2013-05-31T11:54:44.000Z"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
Without moment.js:
var time_to_show = 1509968436; // unix timestamp in seconds
var t = new Date(time_to_show * 1000);
var formatted = ('0' + t.getHours()).slice(-2) + ':' + ('0' + t.getMinutes()).slice(-2);
document.write(formatted);
The /Date(ms + timezone)/ is a ASP.NET syntax for JSON dates. You might want to use a library like momentjs for parsing such dates. It would come in handy if you need to manipulate or print the dates any time later.
If using react:
import Moment from 'react-moment';
Moment.globalFormat = 'D MMM YYYY';
then:
<td><Moment unix>{1370001284}</Moment></td>
Import moment js:
var fulldate = new Date(1370001284000);
var converted_date = moment(fulldate).format(");
if you're using React I found 'react-moment' library more easy to handle for Front-End related tasks, just import <Moment> component and add unix prop:
import Moment from 'react-moment'
// get date variable
const {date} = this.props
<Moment unix>{date}</Moment>
I would like to add that Using the library momentjs in javascript you can have the whole data information in an object with:
const today = moment(1557697070824.94).toObject();
You should obtain an object with this properties:
today: {
date: 15,
hours: 2,
milliseconds: 207,
minutes: 31,
months: 4
seconds: 22,
years: 2019
}
It is very useful when you have to calculate dates.
for people as dumb as myself, my date was in linux epoch
but it was a string instead of an integer, and that's why i was getting
RangeError: Date value out of bounds
so if you are getting the epoch from an api, parseInt it first
var dateTime = new Date(parseInt(1370001284000));
dateTime.toISOString();

Categories