Javascript convert "05/27 11:00pm" to date? - javascript

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.

Related

Javascript input a UTC string

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.

moment.js uses the month as day instead the day

I'm using currently moment.js (moment-with-locales.js - v.2.14.1) in my project. I want to remove the time of my datetime string to get only the date. But if I use the .format() method of moment.js I got an incorrect date.
I want to format this datetime string:
from ' 08.10.2016 11:00 ' to ' 08.10.2016 '
Here is a snipped that I used in my angular project:
var date = moment('08.10.2016 11:00').format('DD.MM.YYYY')
console.log(date)
If I run this I got this output
10.08.2016
instead of
08.10.2016
The funny thing is, if I want to get the timestamp (milliseconds) of my datetime string, it works perfect. Example:
var dateStart = moment('08.10.2016 19:00', 'DD.MM.YYYY HH:mm').valueOf()
console.log(dateStart)
Will return
1475946000000 -> Sat Oct 08 2016 19:00:00 GMT+0200
How can I get the correct Date?
It depends on your locale. en-US locate means moment will parse by "month day year". So, you need to parse with the pattern as well:
var date = moment('08.10.2016 11:00','DD.MM.YYYY HH:mm').format('DD.MM.YYYY')

Unexpected results parsing date strings in JavaScript

I'm working on a JavaScript application. I have two different String dates 31/10/2013 and 1/11/2013 and I create an instance of these two dates with new Date(string).getTime();
But it shows this (the same date ) as the result:
console.log(date_s + " after new date " + date );
31/10/2013 after new date Fri Nov 1 00:00:00 UTC 2013
1/11/2013 after new date Fri Nov 1 00:00:00 UTC 2013
You haven't a valid string in you new Date(string)
Some example to initialize dates
var my_date=new Date(2013,10,31)
and all the documentation on http://www.w3schools.com/js/js_obj_date.asp
31/10/2013 is not a valid date string unless you've got maybe some localization going on. To the default localization settings for en-US, it should be 10/31/2013. What your string means is "month 31 of 2013" which pushes new Date('31/10/2013') to be some time in 2015 because that's where it resolves the date due to that "month 31."
If you want an easy solution, try moment.js - a powerful javascript date parser/formatter/validator/manipulator.
In moment, you can parse date with the syntax like this [doc]:
//this will gives you a correct date object
moment('31/10/2013', 'DD/MM/YYYY').toDate();
Else, you can always welcome to split and rebuild the date object.

Convert UTC date format into javascript format

How can I convert a date from:
Thu, 1 July 2011 22:30:00 to '2011-07-01T13:51:50.417' using javascript.
I get the UTC format when I do a new date.
IE causes me issues when I first create a date object as it shows: NaN
You could generate a new Date-Object and then get the different parts:
var today = new Date();
var year = today.getFullYear(); // Returns 2012
var month = today.getMonth()+1; // Returns the month (zero-based)
...
Then you can create a new string like you need it.
possible duplicate try search next time
stackoverflow question
Try http://www.datejs.com/. It is a JavaScript Date Library with an extended Date.parse method and a Date.parseExact method, which lets you specify a format string. See DateJS APIDocumentation.
and then you can manipulate it as you want
The d3.js library has some very solid routines for date conversions. See https://github.com/mbostock/d3/wiki/Time-Formatting#wiki-parse.

Adding one day to Javascript date + unique formatting?

I've inherited a project for a company I'm working for. Their dates are recorded in the following format:
March 18th, 2011 would be listed as "18 Mar 2011".
April 31st, 2010 would be listed as "31 Apr 2010".
How would I use Javascript to add one day to a date formatted in the above manner, then reconvert it back into the same format?
I want to create a function that adds one day to "18 Mar 2011" and returns "19 Mar 2011". Or adds 1 day to "30 Jun 2011" and returns "1 Jul 2011".
Can anyone help me out?
First of all there is no 31st of April ;)
To the actual issue, the date object can understand the current format when passed as an argument..
var dateString = '30 Apr 2010'; // date string
var actualDate = new Date(dateString); // convert to actual date
var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1); // create new increased date
// now extract the bits we want to crete the text version of the new date..
var newDateString = ('0'+newDate.getDate()).substr(-2) + ' ' + newDate.toDateString().substr(4,3) + ' ' + newDate.getFullYear();
alert(newDateString);
demo at http://jsfiddle.net/gaby/jGwYY/1/
The same extraction using (the better supported) slice instead of substr
// now extract the bits we want to crete the text version of the new date..
var newDateString = ('0'+newDate.getDate()).slice(-2) + ' ' + newDate.toDateString().slice(4,7) + ' ' + newDate.getFullYear();
Demo at http://jsfiddle.net/jGwYY/259/
You would want to convert the date string into a Date object, add one day to the object, and then convert back. Please have a look at the API docs for Date as a starting point.
Most (all?) browsers will be able to parse that date string in with a simple
var parsedDate = new Date(dateString);
Once you have a Date object you can add a day and output a formatted date string using something like underscore.date.
If you discover that some browsers can't parse that date format then you can write a pretty simple regex that will pull apart the date string into its constituent parts, and then build a Date instance by hand.
Also I would strongly recommend doing the parsing in a separate function, and to try and keep dates in a Date representation as much as possible. Parse the string into a date as soon as you can, and format it back into a string as late as you can.

Categories

Resources