Javascript equivalent of php's strtotime()? - javascript

In PHP, you can easily convert an English textual datetime description into a proper date with strtotime().
Is there anything similar in Javascript?

There is not. The closest built-in option is Date.parse(), which parses a very limited subset of what strtotime() can:
var ts = Date.parse("2010-10-29");
It's worth noting that this function returns milliseconds instead of seconds, so you need to divide the result by 1000 to get an equivalent value to PHP's function.

I found this article and tried the tutorial. Basically, you can use the date constructor to parse a date, then write get the seconds from the getTime() method
var d=new Date("October 13, 1975 11:13:00");
document.write(d.getTime() + " milliseconds since 1970/01/01");
Does this work?

Check out this implementation of PHP's strtotime() in JavaScript!
I found that it works identically to PHP for everything that I threw at it.
Update: this function as per version 1.0.2 can't handle this case: '2007:07:20 20:52:45'
(Note the : separator for year and month)
Update 2018:
This is now available as an npm module! Simply npm install locutus and then in your source:
var strtotime = require('locutus/php/datetime/strtotime');

I jealous the strtotime() in php, but I do mine in javascript using moment. Not as sweet as that from php, but does the trick neatly too.
// first day of the month
var firstDayThisMonth = moment(firstDayThisMonth).startOf('month').toDate();
Go back and forth using the subtract() and add() with the endOf() and startOf():
// last day of previous month
var yesterMonthLastDay = moment(yesterMonthLastDay).subtract(1,'months').endOf('month').toDate();

Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.
Try Moment.js - it provides cross-browser functionality for parsing dates:
var timestamp = moment("2013-02-08 09:30:26.123");
console.log(timestamp.milliseconds()); // return timestamp in milliseconds
console.log(timestamp.second()); // return timestamp in seconds

There are few modules that provides similar behavior, but not exactly like PHP's strtotime. Among few alternatives I found date-util yields the best results.

var strdate = new Date('Tue Feb 07 2017 12:51:48 GMT+0200 (Türkiye Standart Saati)');
var date = moment(strdate).format('DD.MM.YYYY');
$("#result").text(date); //07.02.2017
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>
<div id="result"></div>

Maybe you can exploit a sample function like :
function strtotime(date, addTime){
let generatedTime=date.getTime();
if(addTime.seconds) generatedTime+=1000*addTime.seconds; //check for additional seconds
if(addTime.minutes) generatedTime+=1000*60*addTime.minutes;//check for additional minutes
if(addTime.hours) generatedTime+=1000*60*60*addTime.hours;//check for additional hours
return new Date(generatedTime);
}
let futureDate = strtotime(new Date(), {
hours: 1, //Adding one hour
minutes: 45 //Adding fourty five minutes
});
document.body.innerHTML = futureDate;
`

For those looking to convert the datetime to unix timestamp, you can do this using the Moment Library.
For Vue.js, you can do something like
let start = "2022/02/02 02:02:02";
return moment(start).format("x");

Related

How to get hours in moment.js in GMT timezone?

For example if I do for the above date object something like: value.hours(), I get as output 16 instead of 18. I believe it returns the hours in the original GMT time, not like in my date object which is GMT+2. I can of course add 2 to the returned result, but it becomes cumbersome. Is there any way to get the hours correctly in my case?
I'm not sure as to what you've already tried, but I put the following into JSFiddle and it worked like a charm. I am currently in CST in America and it is 8:30 in the morning here. When I ran the snippet below I got today's date at 1:30 PM which I would assume is accurate in difference.
HTML
<div id="m1"></div>
JavaScript
var a = moment.tz(new Date(), "GMT");
document.getElementById('m1').innerHTML = a.format("YYYY MM DD; HH:mm");
The Moment.js documentation states the following in regards to creating a Moment object with a native JavaScript Date object:
You can create a Moment with a pre-existing native JavaScript Date object.
var day = new Date(2011, 9, 16);
var dayWrapper = moment(day);
This clones the Date object; further changes to the Date won't affect the Moment, and vice-versa.
To find the information quoted above quickly, when you reach the Moment.js documentation, it is located under the Parse section under sub-section Date.
To display local time:
value.local();
value.hours(); // 18
To reverse:
value.utc();
value.hours(); // 16
I think that you can solve it by doing what the docs says. Something like this:
moment().tz("America/Los_Angeles").format();
https://momentjs.com/timezone/docs/#/using-timezones/

Javascript: how to convert a UTC date to local one?

Looks like a very simple thing to do? Not afrer reading this http://dygraphs.com/date-formats.html - what a mess!
var time_utc="2016-04-25 20:19:00.306671";
document.write("Local date:"+new Date(time_utc+" UTC")); // Firefox 44.0.2: Invalid Date
How do I print a date in above format adjusted to local time?
The article you provided mentions halfway through the page,
Using hyphens (-) instead of slashes (/) works in WebKit browsers, but
not in IE or FF. Beware the UTC parse of YYYY-MM-DD!
As well as,
Don't try to specify milliseconds. Only recent versions of Chrome will
understand you.
With the date 2016-04-25 20:19:00.306671 you use hyphens and milliseconds. You could modify your time_utc string a bit to make it compatible like so,
var time_utc = "2016-04-25 20:19:00.306671";
time_utc = time_utc.replace(/-/g, "/");
time_utc = time_utc.split(".").shift();
var d = new Date(time_utc);
d.toString();
The above code outputs,
Mon Apr 25 2016 20:19:00 GMT+0200 (CEST)
Have you looked into Moment.js? http://momentjs.com/ It's a handy date-object wrapper that makes date object manipulation easy. Particularly, the local() function provided will give you what you need here.
All you have to do is install moment from npm and then include it in your js file at the top like this:
var moment = require("moment");
Then to change your time_utc variable to local all you have to do is:
var time_utc="2016-04-25 20:19:00.307";
document.write("Local date:"+moment(time_utc).local());
As someone advised me before, it is not wise to include an entire library for a simple, one time function. As a disclaimer, my work requires me to do many date-time calculations and conversions throughout a large project, so including a library for ease is much preferred in my case. However, if you only have to use it this one time, my answer may not be the best.
If you use moment.js, you can use:
var time_utc = "2016-04-25 20:19:00.306671";
var localDate = moment.utc(time_utc).local();
You need append UTC to the string before converting it to a local date in js:
var date = new Date('25/04/2016 4:52:48 PM UTC');
date.toString() // "Mon Apr 25 2016 09:52:48 GMT-0700 (PDT)"

Javascript method Date() is returning wrong date (Feb 9 instead of Sep 2) on my system,

I have a JavaScript method which gets current date and returns its universal time. Below is the code:
function calUTCTime(offset) {
var currentDate = new Date();
var utc = currentDate.getTime() - (currentDate.getTimezoneOffset() * 60000);
var result = new Date(utc + (3600000 * offset));
return result .toLocaleString();
}
Above code is returning wrong date, it is replacing date with month and date format in my system is dd-MM-yyyy, OS is Windows 8. I tried on other system's and the date is correct but on my system it is wrong. Please share suggestions.
That is exactly what I would expect from .toLocaleString(). The browser is determining your language (or "locale") from the OS and using it to choose how to output the string. If you want a generic human-readable date format, try a simple .toString() instead.
If you want complete and total control over how a date is formatted, try a library like moment.js. For example, your above code could be condensed to:
return moment().utc().format("YYYY-MM-DD"); // "2014-09-02"
There is another post that summarizes the differences between the two methods: JavaScript: Difference between toString() and toLocaleString() methods of Date

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

Java date format to JavaScript date format

I would like to be able to convert a Java date format string, e.g. dd/MM/yyyy (07/06/2009) to a JavaScript date format string, e.g. dd/mm/yy (07/06/2009).
Has anyone done this before, or got any idea where I might find some code that already does this?
Edit:
Thanks for all the replies but now I realize my mistake and possibly why so many of you were struggling to understand the question; JavaScript doesn't have a built in date formatting ability. I am using the jQuery UI datepicker and I have been setting its date format, assuming it would be calling a standard JS function at some point, not using its own library! When I googled for formatting strings I jumped straight to the tables of what letters could be used, skipping the bit at the beginning explaining how to use the script.
Anyway I'll have to go ahead and possibly write my own I guess, converting a Java date format string into a jQuery date format string (or as close as possible) - I am working on the i18n of our product and have created a java class that stores the preferred date format string used throughout the application, my intention was to also have the ability to supply any jsps with the format string that is equivalent in JS.
Thanks anyway.
If you just need to pass a date from Java to JavaScript, the best way to do it, I think, would be to convert the Java date to milliseconds using date.getTime(), create a JavaScript date initialized with this milliseconds value with new Date(milliseconds)and then format the date with the means of the JavaScript Date object, like: date.toLocaleString().
You could use my plugin jquery-dateFormat.
// Text
$.format.date("2009-12-18 10:54:50.546", "dd/MM/yyyy");
// HTML Object
$.format.date($("#spanDate").text(), "dd/MM/yyyy");
// Scriptlet
$.format.date("<%=java.util.Date().toString()%>", "dd/MM/yyyy");
// JSON
var obj = ajaxRequest();
$.format.date(obj.date, "dd/MM/yyyy");
A similar topic has been answered here:
Converting dates in JavaScript
I personally have found this to be a rather large pain and took the author's suggestion and used a library. As noted, jQuery datepicker has one that is a viable solution if you can afford the overhead of download for your application or already using it.
Check out moment.js! It's "A lightweight javascript date library for parsing, manipulating, and formatting dates". It is a really powerful little library.
Here's an example...
var today = moment(new Date());
today.format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:32 PM"
// in one line...
moment().format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:32 PM"
Here's another example...
var a = moment([2012, 2, 12, 15, 25, 50, 125]);
a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, March 12th 2012, 3:25:50 pm"
a.format("ddd, hA"); // "Mon, 3PM"
a.format("D/M/YYYY"); // "12/3/2012"
Also, its worth mentioning to checkout date.js. I think the two libraries complement each other.
This JavaScript library should be able to help you.
http://plugins.jquery.com/project/fIsForFormat
(I don't know why they have it as a jQuery Plugin, because it works standalone.)
You'd simply split the original formatted date into its individual elements and then create a new Date Object with those elements. Then, use this library's "Date.f()" method to output it into any format you could want.
For example:
var dateOld = "11/27/2010",
dateArr = date1.split("/"),
dateObj = new Date(dateArr[2], dateArr[0], dateArr[1]),
dateNew = dateObj.f("MMM d, yyyy");
document.write("Old Format: " + dateOld + "<br/>New Format: " + dateNew);
This works fine for me:
<%
Date date = Calendar.getInstance().getTime();
%>
<script>
var d = new Date(<%=date.getTime()%>);
alert(d);
</script>
I suggest you the MomentJS with this Plugin that allow you to convert a Java pattern to a JS pattern (MomentJS)
On Java Side
I recommend passing an Instant string which conforms to ISO 8601 standard.
import java.time.Instant;
class Main {
public static void main(String[] args) {
Instant instant = Instant.now();
// You can pass the following string to JavaScript
String strInstant = instant.toString();
System.out.println(strInstant);
// If the number of milliseconds from epoch is required
long millis = instant.toEpochMilli();
System.out.println(millis);
}
}
Output from a sample run:
2022-12-31T09:40:52.280726Z
1672479652280
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
On JavaScript Side
Now, you can parse the ISO 8601 string on the JavaScript side simply by passing it as a parameter to Date constructor. You can also instantiate the Date object with the number of milliseconds from the epoch.
var date = new Date("2022-12-31T09:40:52.280726Z");
console.log(date.toISOString());
// Or if the number of milliseconds from epoch has been received
date = new Date(1672479652280);
console.log(date.toISOString());
The javascript code in this page implements some date functions and they "use the same format strings as the java.text.SimpleDateFormat class, with a few minor exceptions". It is not the very same as you want but it can be a good start point.
If you just want to format dates my date extensions will do that well - it also parses data formats and does a lot of date math/compares as well:
DP_DateExtensions Library
Not sure if it'll help, but I've found it invaluable in several projects.
If you are using java, take a look at the Simple Date Format class.

Categories

Resources