datejs overwriting Date in javascript - javascript

I am using date js to quickly parse any string into a date and it is working perfectly. However I need to also parse a timestamp.
var temp_string = "1484120122526";
var date = new Date(temp_string);
It gives back
NaN –
Regular javascript Date object does this, but I can't find a way for datejs to do it. And since it overwrites the Date object, I am stuck. Can datejs parse timestamps? or is there a way for me to call new Date() and reference the original date object?

Even though dateJS does indeed overwrite the default js Date class, the fault was on my side, I did not see in the documentation the fact that timestamp has to be an int, as I was looking everywhere in the dateJS documentation not the Date one.
so the code should be:
var temp_int = 1484120122526;
var date = new Date(temp_int);

Related

8601 ISO String to readable date format in Javascript

I'm having a pretty horrid time trying to convert an 8601 into a readable format. The date shows as 'P0DT0H0M10S' and is stored in a var called timeLeft. Every article I find online tells me how to turn dates INTO the 8601 format, but not the other way around.
I tried using moment.js but that seems to revolve around the current date and not one set by my timeLeft var. How do I get this var into a user-friendly format? Thanks
Moment has a duration type:
var duration = moment.duration('P1Y2M3DT4H5M6S');
// user-friendly format
var out = duration.humanize();
snippet.log(out);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
<script src="https://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
First off, that's not an ISO-8601 date (not even close).
Second, momentjs does support parsing a string into a moment, with the moment("20111031", "YYYYMMDD") syntax (from their front page examples).
I'm not sure what the pattern you need would be, but maybe something like [P]D[DT]H[H]M[M]S[S].

momentjs toDate() - timezone gets reset

I am working with momentjs and converting dates to different time zones using convertedDate = moment().utcOffset(timezone).format(). This works well but it is a string and I need to transform it to date object.
I've tried new Date(convertedDate) and moment().utcOffset(timezone).toDate() but that returns my current timezone as a date object. How can I keep the converted timezone?
So I wasn't very far off. The format needs to exclude timezone for it to work. This code finally worked how I needed it to.
convertedDate = new Date(moment().utcOffset('-4').format('YYYY-MM-DD HH:mm'));
A cleaner approach to get a native Date object with time according to the timezone, using moment would be following:
convertedDate = moment.utc(moment.tz(timezone).format('YYYY-MM-DDTHH:mm:ss')).toDate()
PS: assuming two things
you have imported both 'moment' and 'moment-timezone'.
value of timezone is given like 'Asia/Kolkata' instead of an offset value
This should work:
I have the same issue. Just get the Date as a string using the same approach that you are using. Let's say your date is, for example: '2018-08-05T10:00:00'.
Now you need the Date object with correct time. To convert String into object without messing around with timezones, Use getTimezoneOffset:
var date = new Date('2016-08-25T00:00:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() - userTimezoneOffset);
getTimezoneOffset() will return either negative or positive value. This must be subtracted to work in every location in the world.

How do I format a Javascript date like 1950-12-30T18:25:43.511Z

I have an API where I the date need to be formatted like this
1950-12-30T18:25:43.511Z
This format looks somewhat unfamiliar to me, and I'm wondering how I can take a format like this
1950-12-30
and turn it into something like the former. FYI I'm using javascript (express)
You are trying to put the date into ISO format and the native Date object will do that for you, fairly simply, with the .toISOString() method:
var newDate = new Date("0977-03-28");
console.log(newDate.toISOString());
The result of that is: 0977-03-28T00:00:00.000Z (look familiar? :D )
One issue that you will have (if it is an issue), is that, because you only have the date value, and not a time value, the last part of the string will always be T00:00:00.000Z (which is the "time" section of the Date). You'll see that if you use today's date, using var newDate = new Date(); (which captures this instant), the time will be filled in: 2015-02-19T16:50:18.078Z (at the time of testing)
For more information, see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
(Note: in IE, this only works in v9 or later, though, that link also has a polyfill for older IE versions)

Moment.js transform to date object

Using Moment.js I can't transform a correct moment object to a date object with timezones. I can't get the correct date.
Example:
var oldDate = new Date(),
momentObj = moment(oldDate).tz("MST7MDT"),
newDate = momentObj.toDate();
console.log("start date " + oldDate)
console.log("Format from moment with offset " + momentObj.format())
console.log("Format from moment without offset " + momentObj.utc().format())
console.log("(Date object) Time with offset " + newDate)
console.log("(Date object) Time without offset "+ moment.utc(newDate).toDate())
Use this to transform a moment object into a date object:
From http://momentjs.com/docs/#/displaying/as-javascript-date/
moment().toDate();
Yields:
Tue Nov 04 2014 14:04:01 GMT-0600 (CST)
As long as you have initialized moment-timezone with the data for the zones you want, your code works as expected.
You are correctly converting the moment to the time zone, which is reflected in the second line of output from momentObj.format().
Switching to UTC doesn't just drop the offset, it changes back to the UTC time zone. If you're going to do that, you don't need the original .tz() call at all. You could just do moment.utc().
Perhaps you are just trying to change the output format string? If so, just specify the parameters you want to the format method:
momentObj.format("YYYY-MM-DD HH:mm:ss")
Regarding the last to lines of your code - when you go back to a Date object using toDate(), you are giving up the behavior of moment.js and going back to JavaScript's behavior. A JavaScript Date object will always be printed in the local time zone of the computer it's running on. There's nothing moment.js can do about that.
A couple of other little things:
While the moment constructor can take a Date, it is usually best to not use one. For "now", don't use moment(new Date()). Instead, just use moment(). Both will work but it's unnecessarily redundant. If you are parsing from a string, pass that string directly into moment. Don't try to parse it to a Date first. You will find moment's parser to be much more reliable.
Time Zones like MST7MDT are there for backwards compatibility reasons. They stem from POSIX style time zones, and only a few of them are in the TZDB data. Unless absolutely necessary, you should use a key such as America/Denver.
.toDate did not really work for me, So, Here is what i did :
futureStartAtDate = new Date(moment().locale("en").add(1, 'd').format("MMM DD, YYYY HH:MM"))
hope this helps
Since momentjs has no control over javascript date object I found a work around to this.
const currentTime = new Date();
const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss");
const convertTimeObject = new Date(convertTime);
This will give you a javascript date object with the converted time
The question is a little obscure. I ll do my best to explain this. First you should understand how to use moment-timezone. According to this answer here TypeError: moment().tz is not a function, you have to import moment from moment-timezone instead of the default moment (ofcourse you will have to npm install moment-timezone first!). For the sake of clarity,
const moment=require('moment-timezone')//import from moment-timezone
Now in order to use the timezone feature, use moment.tz("date_string/moment()","time_zone") (visit https://momentjs.com/timezone/ for more details). This function will return a moment object with a particular time zone. For the sake of clarity,
var newYork= moment.tz("2014-06-01 12:00", "America/New_York");/*this code will consider NewYork as the timezone.*/
Now when you try to convert newYork (the moment object) with moment's toDate() (ISO 8601 format conversion) you will get the time of Greenwich,UK. For more details, go through this article https://www.nhc.noaa.gov/aboututc.shtml, about UTC. However if you just want your local time in this format (New York time, according to this example), just add the method .utc(true) ,with the arg true, to your moment object. For the sake of clarity,
newYork.toDate()//will give you the Greenwich ,UK, time.
newYork.utc(true).toDate()//will give you the local time. according to the moment.tz method arg we specified above, it is 12:00.you can ofcourse change this by using moment()
In short, moment.tz considers the time zone you specify and compares your local time with the time in Greenwich to give you a result. I hope this was useful.
To convert any date, for example utc:
moment( moment().utc().format( "YYYY-MM-DD HH:mm:ss" )).toDate()
let dateVar = moment('any date value');
let newDateVar = dateVar.utc().format();
nice and clean!!!!
I needed to have timezone information in my date string. I was originally using moment.tz(dateStr, 'America/New_York').toString(); but then I started getting errors about feeding that string back into moment.
I tried the moment.tz(dateStr, 'America/New_York').toDate(); but then I lost timezone information which I needed.
The only solution that returned a usable date string with timezone that could be fed back into moment was moment.tz(dateStr, 'America/New_York').format();
try (without format step)
new Date(moment())
var d = moment.tz("2019-04-15 12:00", "America/New_York");
console.log( new Date(d) );
console.log( new Date(moment()) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
moment has updated the js lib as of 06/2018.
var newYork = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london = newYork.clone().tz("Europe/London");
newYork.format(); // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format(); // 2014-06-01T17:00:00+01:00
if you have freedom to use Angular5+, then better use datePipe feature there than the timezone function here. I have to use moment.js because my project limits to Angular2 only.
new Date(moment()) - could give error while exporting the data column in excel
use
moment.toDate() - doesn't give error or make exported file corrupt

Trying to parse date using new Date(). but keep getting wrong results

I am trying to parse a date string i get from php through ajax call(which is irrelevant for now) using new Date().
however i keep getting wrong results.
My string is 2013-05-09 20:56:17
When i do
var something = new Date("2013-05-09 20:56:17");
alert(something.getMonth());
It keeps alerting 0
In my opinion for some reason new date cant parse this string.
Is there a way to specify the date format for new Date() in JS ?
My current solution is to import php's: date() and strtotime() and use them :
alert(date('m', strtotime("2013-05-09 20:56:17")));
This works however I have to use external js lib and I am pretty sure there is a better JS way to achieve that.
If you use slashes instead of hyphens, it works:
var something = new Date("2013/05/09 20:56:17");
alert(something.getMonth());
It's easy enough to replace any hyphens in a string with slashes first if you need to (say, if you were getting the date string from somewhere else):
var something = new Date("2013-05-09 20:56:17");
something = something.replace('-', '/');
It seems JavaScript's Date constructor doesn't recognize date formats with hyphens, or at least not that particular format.
Choose a different format specifier in PHP for your ajax dates. The format you expect and the format expected by the javascript are different.
var something = new Date("2013-05-09T20:56:17");
Note the 'T' which appears as a literal separator and marks the beginning of time per ISO 8601
Reference for various [browser] javascript date formats
W3 DateTime
Microsoft IE DateTime
Mozilla [Firefox] DateTime
Google DateJs
And lastly, the PHP date format specifier list:
PHP Date
PHP DateTime
Note the 'DATE_ISO8601'; but I suggest not using that at this time. Instead use 'DATE_ATOM' which may produce a date format more widely supported (comments suggest it makes iPhones happier and no issues with other browsers).
To use it in PHP:
$something = new DateTime('NOW');
echo $something->format('c');
echo $something->format(DateTime::ATOM);

Categories

Resources