Convert Normal Date to TimeStamp JavaScript - javascript

I have this date
Sep 7, 2019, 1:00 PM CEST
and want to convert it into a timestamp.
How would I go about doing this?

Replace CEST -> (CEST) and try to convert like below,
new Date("Sep 7, 2019, 1:00 PM CEST".replace('CEST', '(CEST)'))
Solution implemented based on this valuable article. Credit goes to article author :)

This answer is more of a pseudo-code then an exact javascript code.
The format of the string (posted by OP) is not supported natively. One of the answers used moment's moment function with second argument to parse the timezone i.e. CEST part in the querying string basically, but I found that conversion faulty too - https://www.epochconverter.com/timezones?q=1567841400&tz=Europe%2FBerlin - wondering what is 1567841400 try running this answer - https://stackoverflow.com/a/57830429/7986074
So the code would look like this -
Extract the time-zone attribute from the string - i.e. CEST - one may use ''.substr
Convert the extracted time-zone string to the UTC offset.
Use the UTC offset to make the date string.
Parse the string so made with utilities such as Date or moment

Did you try passing that string directly into the Date constructor? But before you have to get rid of the timezone. Here is an easy example:
// 1. A variable with your date as a string literal
const dateStr = "Sep 7, 2019, 1:00 PM CEST"
// 2. Get rid of the timezone and use the result to instantiate a new date
const d = new Date(dateStr.slice(0,-4))
// 3. Now that you have your date instance, use getTime() method to get the timestamp
const timestamp = d.getTime()
Hope my answer can help you!

You might need to convert your CEST to GMT+0200 which contains the timezone and the offset as well.
const date = new Date('Sep 7, 2019, 1:00 PM CEST'.replace('CEST', 'GMT+0200'));
console.log(date);

Related

Convert the epoch timestamp to time of 12:01 am

I'd like to get the Epoch timestamp of a date being entered by a user, but convert the time to 12:01 am in JavaScript.
How do I do that?
Take the timestamp and pass it while creating a instance of the Date class like:
let timestamp = 1629289414;
let dateInstance = new Date(timestamp * 1000);
console.log(dateInstance); // Wed Aug 18 2021 14:23:34....
From there on you have many ways to work with dateInstance. To get the 12:00am result from this it's more a string manipulation/adjusting thing.
Just check out the documentation on the the javascript Date instance: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date
If you have further questions just post the code you've written and maybe I can help you out

the date in Javascript is swapping between day and month in?

I Have date as a string 10/06/1991 when I need to convert to a date object the day and month value is swiping like this Sun Oct 06 1991 00:00:00 GMT+0200 (GMT+03:00), but if I reverse my string to 1991/06/10 it's correct after converting.
is there any idea how to solve it?
You cannot parse string to date using Date object unless it is in ISO form. Here later date - 1991/06/10 is in in correct order so js can make correct date object.
For your case, you can use any other library like moment for parse your given date 10/06/1991 by giving its format to moment, example is given below -
console.log(moment("10/06/1991", "DD/MM/YYYY").toDate());
<script src="https://momentjs.com/downloads/moment-with-locales.min.js"></script>

Any way to parse a time string using Moment.js but ignore timezone info?

Given the volume of Timezone questions, I would have thought to be able to find the answer to this issue, but haven't had any success.
Is there a way using moment.js to parse an ISO-8601 string but have it parsed in my local timzeone? Essentially I want to ignore the timezone information that is supplied in the ISO string.
For example, if I am in EDT timezone:
var x = moment( "2012-12-31T00:00:00+0000" );
will give me:
"2012-12-30T19:00:00-5000"
I'm looking to ignore the timezone info and just have it give me a moment equivalent of "2012-12-31T00:00:00-5000" local time (EDT).
I don't think you really want to ignore the offset. That would ultimately just be replacing the offset you provided with one from your local time zone - and that would result in a completely different moment in time.
Perhaps you are just looking for a way to have a moment retain the time zone it was given? If so, then use the moment.parseZone function. For example:
var m = moment.parseZone("2012-12-31T00:00:00+0000");
var s = m.format(); // "2012-12-31T00:00:00+00:00"
You could also achieve this with moment.utc. The difference is that moment.parseZone will retain whatever offset you give it, while moment.utc will adjust to UTC if you give it a non-zero offset.
I solved this by supplying a format as the second argument, and using Moment's method of escaping characters, and wrapped square brackets around the timezone.
moment("2016-01-01T05:00:00-05:00", "YYYY-MM-DDTHH:mm:ss[Z]").startOf("hour").format()
This will still create moment objects using your local time zone, but it won't do any sort of auto-timezone calculation. So the above example will give you 5am regardless of timezone supplied.
I know I'm late to the party, I had the same question and my searches didn't bring me any closer. I broke down and read the documentation and there is an option in moment for a String + Format:
String + Format docs
moment(String, String);
moment(String, String, String);
moment(String, String, Boolean);
moment(String, String, String, Boolean);
and more words, then this:
Unless you specify a time zone offset, parsing a string will create a date in the current time zone.
moment("2010-10-20 4:30", "YYYY-MM-DD HH:mm"); // parsed as 4:30 local time
moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z"); // parsed as 4:30 UTC
The part that gave me pause was the example that was used to parse local time omitted the +0000, which lead me to think the input string needed to have that removed, but it doesn't.
example:
var time = "2012-12-31T00:00:00+0000";
var x = moment(time); // Sun Dec 30 2012 19:00:00 GMT-0500
var y = moment(time,'YYYY-MM-DD'); //Mon Dec 31 2012 00:00:00 GMT-0500
You can ignore the browser's timezone completely by creating a new moment using moment.utc() instead of moment().
For example, if you are trying to work purely with a UTC date/time of the browser's current time but want to discard its timezone data, you can recreate the browser's current time into a UTC format using the following:
let nowWithTimezone = moment();
let nowInUtc = moment.utc(nowWithTimezone.format('MM/DD/YYYY HH:mm'), 'MM/DD/YYYY HH:mm');
Further documentation on moment.utc(): https://momentjs.com/docs/#/parsing/utc/
If you know for sure your input string is in the ISO-8601 format, you could just strip off the last 5 digits and use that in the Moment constructor.
var input = "2012-12-31T00:00:00+0000"
input = input.substring(0, input.length-5)
moment(input).toString()
> "Mon Dec 31 2012 00:00:00 GMT-0600"
There are valid reasons to do what the OP is asking for. The easiest way to do this with Moment is using its parseZone(date) method. No futzing around with string manipulation or multiple calls. It effectively parses the date string as though it were in the browser's local time zone.
This is difficult task to do with MomentJS, it will basically depend as well on your current timezone.
Documentation as well is vague for this specific task, the way I solved the issue on my side was by adding hours to the date before converting it to JSON format.
var dt = moment("Sun Sep 13 2015 00:00:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400", false);
var date = dt.add(2, 'hour').toJSON();
console.log(date); //2015-09-13T00:00:00.000Z
Momentjs default logic will format the given time with local timezone. To format original date, I wrote a function:
https://github.com/moment/moment/issues/2788#issuecomment-321950638
Use moment.parseZone to convert without taking into account the timezone.
const moment = require('moment')
const dateStr = '2020-07-21T10:00:00-09'
const date = moment.parseZone(dateStr)
console.log(date.format('MM-DD-YY HH:mm A')) // 07-21-20 10:00 AM
Try here link to docs
The best way is to use:
dt = moment("Wed Sep 16 2015 18:31:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400",true);
And to display convert again to desired timezone:
dt.utcOffset("-04:00").toString()
output > Wed Sep 16 2015 18:31:00 GMT-0400

Use JavaScript to convert a date string with timezone to a date object in local time

The format of my date string looks like this: yyyy-MM-ddTHH:mm:ss-0Z00
Example 1: 2010-03-05T07:03:51-0800
Example 2: 2010-07-01T20:23:00-0700
I need to create a date object using these date strings. new Date() does not work on this string.
Please help me convert these date strings into a date objects with the local timezone.
Thank you!
Edit: I am using this in Pentaho Data Integration 4.3.0.
Take my timezone as an example (AEST):
function parseDate(str_date) {
return new Date(Date.parse(str_date));
}
var str_date = "2015-05-01T22:00:00+10:00"; //AEST time
var locale_date = parseDate(str_date);
locale_date: Fri May 01 2015 22:00:00 GMT+1000 (AEST)
var str_date = "2015-05-01T22:00:00+00:00" //UTC time
var locale_date = parseDate(str_date);
locale_date: Sat May 02 2015 08:00:00 GMT+1000 (AEST)
You can use a library such as Moment.js to do this.
See the String + Format parsing.
http://momentjs.com/docs/#/parsing/string-format/
The following should parse your date you provided, but you may need to modify it for your needs.
var oldDate = "2010-03-05T07:03:51-0800";
var dateObj = moment(oldDate, "YYY-MM-DDTHH:mm:ssZ").toDate();
Alternatively, see Moment's String parser, which looks like it is in the format you provided, with the exception of a space between the seconds of the time and the time zone.
http://momentjs.com/docs/#/parsing/string/
Alternative
A second way of doing this is Date.js, another library that seems to parse the format just fine. http://www.datejs.com
Date String:
var strDate = "2010-07-01T20:23:00-0700";
To local time representation in native JS Date object:
var ltzDate = (new Date(strDate)).toLocaleString();

Formatting ISODate from Mongodb

In Mongodb I am storing date and time in ISODate format.
Which looks like this
ISODate("2012-07-14T01:00:00+01:00")
Using nodejs/javascript, how can I display the time component so I would get something like this
Time : 01:00
I am using momentjs to make this easier but from what I can tell momentjs does seem to support the ISODate format.
Thanks for you help.
JavaScript's Date object supports the ISO date format, so as long as you have access to the date string, you can do something like this:
> foo = new Date("2012-07-14T01:00:00+01:00")
Sat, 14 Jul 2012 00:00:00 GMT
> foo.toTimeString()
'17:00:00 GMT-0700 (MST)'
If you want the time string without the seconds and the time zone then you can call the getHours() and getMinutes() methods on the Date object and format the time yourself.
MongoDB's ISODate() is just a helper function that wraps a JavaScript date object and makes it easier to work with ISO date strings.
You can still use all of the same methods as working with a normal JS Date, such as:
ISODate("2012-07-14T01:00:00+01:00").toLocaleTimeString()
// Note that getHours() and getMinutes() do not include leading 0s for single digit #s
ISODate("2012-07-14T01:00:00+01:00").getHours()
ISODate("2012-07-14T01:00:00+01:00").getMinutes()
you can use mongo query like this
yearMonthDayhms: { $dateToString: { format: "%Y-%m-%d-%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}
HourMinute: { $dateToString: { format: "%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}
// from MongoDate object to Javascript Date object
var MongoDate = {sec: 1493016016, usec: 650000};
var dt = new Date("1970-01-01T00:00:00+00:00");
dt.setSeconds(MongoDate.sec);

Categories