I'm working on a project right now where I want to get an array of dates between two end points. I've got that code working perfectly when I hard code the start and end date in.
My problem is when I used an input, the code doesn't work. How can I convert a normal date input into a UTC string?
Here's an example of what I'm on about: https://jsfiddle.net/mksvh95y/5/
<input type="date" id="bubbles" placeholder = "enter date">
<button onclick="getDate()"> Click me to get date</button>
<script>
function getDate(){
var water = document.getElementById("bubbles").value;
alert(water);
//alert(water.toUTCString());
var fire = new Date (2018,10,15);
alert(fire);
}
I want the get the 'water' variable to be formatted like the 'fire' variable.
I saw there's .toUTCstring(), but that doesn't work
This is possibly a duplicate of Why does Date.parse give incorrect results, but here's an answer that may be more suitable.
The value of a date input is an ISO 8601 format date string in the format "YYYY-MM-DD", which is what you should see from:
alert(water); // something like 2018-06-21
The format of the string returned by Date.prototype.toString is implementation dependent (though ECMAScript 2019 will standardise it). That's the format you're getting from:
alert(fire) // e.g. Thu Jun 21 2018 00:00:00 GMT+1000 (AEST)
One fix is to convert the string from the date input to a Date, then use the default toString for both outputs. But your problem then is that parsing of the ISO 8601 date string is UTC, so the dates will be different by the host timezone offset, e.g.
console.log(new Date('2018-06-21').toString()); // 21 Jun 2018
console.log(new Date(2018, 5, 21).toString()); // 21 Jun 2018
So you need to parse the string from the input as local using a simple function like:
function parseISOLocal(s) {
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2]);
}
console.log(parseISOLocal('2018-06-21').toString());
console.log(new Date(2018, 5, 21).toString());
If you want to use a library like moment.js, it will parse ISO 8601 formatted date strings as local (which is consistent with ISO 8601), then convert it to a plain Date and use the default toString, e.g.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<input type="date"
onchange="console.log(moment(this.value).toDate().toString())">
I strongly recommend using the excellent MomentJS library for date mainpulation, as native support is poor:
function getDate(){
var water = document.getElementById("bubbles").value;
var waterMoment = moment(water);
alert(water.utc().format()); //outputs a UTC date string
var fire = new Date (2018,10,15);
alert(fire);
}
See the moment.utc() function and the moment.format() function for more details.
Related
The codes below return current UTC datetime in string format.
But i am looking for a function in javascript that return current utc datetime in datetime format.
It seems there is no such that function in javascript.
var dateTime_now = new Date();
var dateTime_now_utc_str = dateTime_now.toUTCString();
alert(dateTime_now_utc_str);
.toISOString() is what you want, not .toUTCString()
You already have the Javascript internal DateTime format in the variable dateTime_now. So I think you do want a string output, but not the string Sun, 05 Dec 2021 06:11:15 GMT, because it contains useless strings like Sun and useful, but non-numerical strings like Dec. I am guessing you do want a string output, but containing digits and separators and no words.
var dateTime_now = new Date();
var dateTime_now_utc_str = dateTime_now.toISOString();
console.log(dateTime_now_utc_str);
// Result: 2021-12-05T06:10:54.299Z
Why?
A detailed explanation of why is given here, by me:
https://stackoverflow.com/a/58347604/7549483
In short, UTC simply means "in the timezone of GMT+0", while ISO is the name of the format yyyy-mm-dd etc. The full name of the date format is ISO 8601.
Doing this with the date-functions.js library (used e.g. in datetimepicker jQuery plugin):
Date.parseDate('2018-03-10 12:12', 'Y-m-d H:i')
gives:
Sat Mar 10 2018 12:12:00 GMT+0100 (Paris, Madrid)
How to get the result as Unix timestamp or GMT / UTC time instead?
A string like '2018-03-10 12:12' will usually be parsed as local as there is no timezone offset. It's also not ISO 8601 compliant so using the built-in parser will yield different results in different browsers.
While you can use a library, to parse it as UTC and get the time value is just 2 lines of code:
function toUTCTimeValue(s) {
var b = s.split(/\D/);
return Date.UTC(b[0],b[1]-1,b[2],b[3],b[4]);
}
// As time value
console.log(toUTCTimeValue('2018-03-10 12:12'));
// Convert to Date object and print as timestamp
console.log(new Date(toUTCTimeValue('2018-03-10 12:12')).toISOString());
var date = new Date('2018-03-10 12:12'.replace(' ', 'T'));
// Unix
console.log(Math.floor(date.getTime() / 1000));
// UTC
console.log(date.toUTCString());
As always, please have a look at the documentation at MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Use MomentJS instead. You can specify exactly what format the string you're parsing is in. MomentJS can then provide you with the underlying Date object, unix timestamp as well as convert to UTC.
var d = moment('2018-03-10 12:12', 'YYYY-MM-DD HH:mm');
console.log(d.toDate());
console.log(d.unix());
console.log(d.utc().toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
You could of course also parse the date as UTC too instead of treating it as a local time.
moment.utc('2018-03-10 12:12', 'YYYY-MM-DD HH:mm');
NOTE Bit difficult for me to test UTC as I'm in the UK and GMT and UTC are virtually the same.
I have a date string with this format
2016-08-12T15:22:43.698Z
how can I parse it to obtain a resulting string that looks like
Aug 12, 2016 5:22 PM
Is there libraries/component that could facilitate such operation or shall I do it manually by coping each part of the String?
var date = new moment('2016-08-12T15:22:43.698Z');
console.log(date.format('MMM DD, YYYY h:mm A'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.js"></script>
Use momentjs, and format the moment obj as your requirement.
If the string is in the ISO standard format, which it looks like it is, you can use Date.parse() or new Date() to turn the value into a Date object. With a Date, you can call toString() or toLocaleString() to get the date formatted in local time.
If you are targeting modern JavaScript environments, Intl.DateTimeFormat provides a very complete API for formatting the date in different locales.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
This works perfectly fine on the client-side, at first:
var timeOfMessageSent = new Date();
console.log(timeOfMessageSent); // Mon May 22 2017 14:03:13 GMT+0200 (Romance Summer Time)
var day = timeOfMessageSent.getDay(); // 1
console.log("this is the day: ",day);
However, after having sent the date to the server, and then sent it back to the client, it doesn't work.
Now the date is displayed like this: 2017-05-22T12:03:13.437Z
I guess that's why getDate doesn't work.
How do I make sure that the date is displayed like at first? e.g. 2017-05-22T12:03:13.437Z
Make your server date string to date object.
var timeOfMessageSent = new Date();
console.log(timeOfMessageSent); // Mon May 22 2017 14:03:13 GMT+0200 (Romance Summer Time)
var day = timeOfMessageSent.getDay(); // 1
console.log("this is the day: ",day);
var newDate = new Date("2017-05-25T12:19:55.982Z"); // give your server date and return as date object
var newDay = newDate.getDay();
console.log("this is the new day: ", newDay);
It seems the date gets returned by the server as an ISO string. You have to create a new Date instance from this string.
Using strings to create date objects are usually discouraged, but an ISO date string is standard and the safest date string format to initialize a date object from.
A Javascript date object is not something that can be part of JSON, so it needs to be converted to a string or a number in order to be transmitted through a JSON API. That's why the server returns this ISO string representation of the date.
An alternative to ISO string commonly used by JSON APIs is to convert the date to a number representing the milliseconds of the date. Both varieties can be converted back to a Javascript date object with the date constructor: new Date(dateValue)
The ISO string you get back can be modified to your preference using moment.js. With that library you can show the date however you want.
How does one convert a string of a date without a year to a JS Date object? And how does one convert a date string with a year and a time into a JS Date object?
Many different date formats can be converted to date objects just by passing them to the Date() constructor:
var date = new Date(datestring);
Your example date doesn't work for two reasons. First, it doesn't have a year. Second, there needs to be a space before "pm" (I'm not sure why).
// Wed May 27 2009 23:00:00 GMT-0700 (Pacific Daylight Time)
var date = new Date("2009/05/27 11:00 pm")
If the date formats you're receiving are consistent, you can fix them up this way:
var datestring = "05/27 11:00pm";
var date = new Date("2009/" + datestring.replace(/\B[ap]m/i, " $&"));
I'd use the Datejs library's parse method.
http://www.datejs.com/
I tried your example and it worked fine...
5/27 11:00pm
Wednesday, May 27, 2009 11:00:00 PM
I have used the Dojo time parser to do things like this:
Check it out:
http://api.dojotoolkit.org/jsdoc/HEAD/dojo.date.locale.parse
Not the cleanest, but works:
var strDate = '05/27 11:00pm';
var myDate = ConvertDate(strDate, '2009');
function ConvertDate(strWeirdDate, strYear)
{
strWeirdDate = strWeirdDate.replace(/ /, '/' + strYear + ' ');
return new Date(strWeirdDate);
}
Probably want to trim the string first as well.
Just another option, which I wrote:
DP_DateExtensions Library
It has a date/time parse method - pass in a mask and it'll validate the input and return a data object if they match.
Also supports date/time formatting, date math (add/subtract date parts), date compare, speciality date parsing, etc. It's liberally open sourced.