No format support in Date object [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Extending JavaScript's Date.parse to allow for DD/MM/YYYY (non-US formatted dates)?
Convert dd-mm-yyyy string to date
Entered a date in textbox, for example: 05/09/1985, and I wanted to convert it to 05-Sep-1985 (dd-MMM-yyyy) format. How would I achieve this? Note that the source format may be dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format.
Code Snippet:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val());
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
This code returns 09-May-1985 but I want 05-Sep-1985. Thanks.

You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations
Then you can do things like:
var day = moment("12-25-1995", "MM-DD-YYYY");
or
var day = moment("25/12/1995", "DD/MM/YYYY");
then operate on the date
day.add('days', 7)
and to get the native javascript date
day.toDate();

Update
Below you've said:
Sorry, i can't predict date format before, it should be like dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format finally i wanted to convert all this format to dd-MMM-yyyy format.
That completely changes the question. It'll be much more complex if you can't control the format. There is nothing built into JavaScript that will let you specify a date format. Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd, although in practice almost all browsers also support yyyy/mm/dd as well. But other than that, you have to write the code yourself or (and this makes much more sense) use a good library. I'd probably use a library like moment.js or DateJS (although DateJS hasn't been maintained in years).
Original answer:
If the format is always dd/mm/yyyy, then this is trivial:
var parts = str.split("/");
var dt = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[0], 10));
split splits a string on the given delimiter. Then we use parseInt to convert the strings into numbers, and we use the new Date constructor to build a Date from those parts: The third part will be the year, the second part the month, and the first part the day. Date uses zero-based month numbers, and so we have to subtract one from the month number.

Date.parse recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy, so the result is wrong.
To fix this, you need either to parse the input yourself (e.g. with String.split) and then manually construct a Date object, or use a more full-featured library such as datejs.
Example for manual parsing:
var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
Example using date.js:
var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");

Try this:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1') change day/month position.

See this http://blog.stevenlevithan.com/archives/date-time-format
you can do anything with date.
file : http://stevenlevithan.com/assets/misc/date.format.js
add this to your html code using script tag and to use you can use it as :
var now = new Date();
now.format("m/dd/yy");
// Returns, e.g., 6/09/07

Related

Transforming date string from one timezone to another in JavaScript

I have spent several hours trying to figure out how JavaScript works with dates. I have come across this question, but it does not seem to asnwer my specific question.
My input is a string like this:
"2018-02-19T07:00:00Z"
My goal is to transform this into a datetime which would differ from the original date by 4 hours - WITHOUT ANY TIMEZONE (!):
"2018-02-19T11:00:00Z"
Is it possible in JavaScript ?
Check out all the functions relating to "UTC" and "ISO" on the Date docs.
var input = "2018-02-19T07:00:00Z";
var t = new Date(input);
t.setUTCHours(t.getUTCHours()+4)
var iso = t.toISOString().replace(/\.\d+/,'');
console.log(iso);
(I added a little regex to get rid of the milliseconds so it matches your expected output, you can remove that if the miliseconds don't matter, it's valid ISO either way.)
It's 4 lines of code, you do not need a library.
In addition to #Occam'sRazor answer, you could also do it without using the Date object, by using some String manipulations :
var str = "2018-02-19T07:00:00Z";
var timeZoneHours = +str.split('-').pop().split(':')[0].split('T').pop() + 4;
console.log(timeZoneHours);
str = str.substring(0,str.indexOf(':') -2) + (timeZoneHours < 10 ? '0' + timeZoneHours.toString() : timeZoneHours.toString()) + str.substring(str.indexOf(':'), str.length);
console.log(str);

Javascript: How to convert exif date time data to timestamp? [duplicate]

This question already has answers here:
javascript: how to parse a date string
(4 answers)
Closed 5 years ago.
In javascript, while using exif-js to extract metadata of an image file, I am getting date time format as 2017:03:09 14:49:21.
The value in the DateTimeOriginal property is formatted as YYYY:MMY:DD HH:MM:SS. When I use var d = new Date(2017:03:09 14:49:21), it returns NaN. It's the colons in between the YYYY, MM, and DD which causes problem.
How to solve this problem?
Thanks in advance.
Don't use the built-in parser (i.e. Date constructor or Date.parse) for parsing strings as it's largely implementation dependent and unreliable. If you can trust the date to be valid, then the following will do:
/* Parse date string in YYYY-MM-DD hh:mm:ss format
** separator can be any non-digit character
** e.g. 2017:03:09 14:49:21
*/
function parseDate(s) {
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
}
console.log(parseDate('2017:03:09 14:49:21').toString());
It's fairly easy to add validation to the values. Otherwise, use a library and make sure you specify the format to parse.
My recommendation would be to use Moment (http://momentjs.com/docs/), as it provides clean parsing of dates. With Moment, what you want is this:
var tstamp = moment("2017:03:09 14:49:21", "YYYY:MM:DD HH:mm:ss");
var date = tstamp.toDate();
You can do simple string manipulation and create date if the format is always the same, as:
var str = "2017:03:09 14:49:21".split(" ");
//get date part and replace ':' with '-'
var dateStr = str[0].replace(/:/g, "-");
//concat the strings (date and time part)
var properDateStr = dateStr + " " + str[1];
//pass to Date
var date = new Date(properDateStr);
console.log(date);

Convert Date String(yymmdd) to Date Object in JS

I have a date string in "yymmdd" format i want to convert it into date object in JS
the input string is "161208"
I have tried code below
var mydate = new Date(InputDate);
but it says invalid date.
Here is the fiddle
https://jsfiddle.net/4ry0hL4t/
the basic need is that, I have a date string in "yymmdd" format and i have to convert it to different date formats like ("yyyy/mm/dd, yy-mm-dd","yy/mm").
Check my answer.
Basically you first need to give a proper format to your string. You can either do it manually or use moment.js.
stringFormat = moment(dateObject).format("YYYY-MM-DDTHH:mm:ss");
date = new Date(stringFormat);
This is also really helpful to understand how the different string formats are compatible with different browsers.
I'm not sure if this is what you're after?
var s = '161208';
var dt = new Date('20' + s.substring(0, 2) + '-' + s.substring(2, 4) + '-' + s.substring(4));

Regular Expression Pattern match for Date

I am trying to extract the date from the following object (that has been stringified.)
I am new to regular expressions, and not sure how to go about it.
I tried /^(\d{4})\-(\d{1,2})\-(\d{1,2})$/gmi -> but it didnot work.
{"Date":"2016-05-16","Package Name":"com.myapp.mobile","Current Device Installs":"15912","Daily Device Installs":"41","Daily Device Uninstalls":"9","Daily Device Upgrades":"3","Current User Installs":"12406","Total User Installs":"23617","Daily User Installs":"27","Daily User Uninstalls":"8"}
Don't use a Regex here.
Do JSON.parse(str).Date, unless there is a really good reason not to (you haven't stated one in your question)
If you want to turn the string "2016-05-16" into 3 variables for Year, Month and day (without using a date library), I'd just use .split():
dateArray = "2016-05-16".split("-")
var year = dateArray[0], month = dateArray[1], day = dateArray[2];
Your regex matches fine, just don't use the /gmi flags
"2016-05-16".match(/^(\d{4})\-(\d{1,2})\-(\d{1,2})$/)
You can make it a bit simpler yet..
"2016-05-16".match(/(\d{4})-(\d{2})-(\d{2})/)
But, you really should be using a library for this, like moment.js, or at least Date which will work fine because this ISO-8601.
const date = new Date("2016-05-16");
date.getYear();
As suggested in comments, you can get the date by parsing the JSON (trimmed in the following for convenience):
var s = '{"Date":"2016-05-16","Package Name":"com.myapp.mobile"}';
var dateString = JSON.parse(s).Date;
document.write(dateString);
If you want a Date object, you can then parse the string. Note that using either the Date constructor or Date.parse for parsing strings is not recommended due to browser inconsistencies. Manually parsing an ISO date is fairly simple, you just need to decide whether to parse it as local or UTC.
Since ECMA-262 requires the date–only ISO format to be parsed as UTC, the following function will do that reliably (and return an invalid date for out of range values):
/* Parse an ISO 8601 format date string YYYY-MM-DD as UTC
** Note that where the host system has a negative time zone
** offset the local date will be one day earlier.
**
** #param {String} s - string to parse
** #returs {Date} date for parsed string. Returns an invalid
** Date if any value is out of range
*/
function parseISODate(s) {
var b = s.split(/\D/);
var d = new Date(Date.UTC(b[0], b[1]-1, b[2]));
return d && d.getMonth() == b[1]-1? d : new Date(NaN);
}
var d = parseISODate('2016-05-16');
document.write('UTC date: ' + d.toISOString() + '<br>' +
'Local date: ' + d.toString());

Formatting the Date in JavaScript

Using newDate() function in Java script, I am able to get today's date. I am getting the date in the format 3/3/2009 (d/m/yyyy). But i actually need the date in the format 2009-03-03 (yyyy-mm-dd). Can anyone pls let me know how to format the date as i require?
You usually have to write your own function to handle the formatting of the date as javascript doesn't include nice methods to format dates in user defined ways. You can find some nice pieces of code on the net as this has been done to death, try this:
http://blog.stevenlevithan.com/archives/date-time-format
Edit: The above code seems to be really nice, and installs a cool 'format' method via the date object's prototype. I would use that one.
If you want to roll-your-own, which is not too difficult, you can use the built-in javascript Date Object methods.
For example, to get the current date in the format you want, you could do:
var myDate = new Date();
var dateStr = myDate.getFullYear +
'-' + (myDate.getMonth()+1) + '-' + myDate.getDate();
You may need to zero-pad the getDate() method if you require the two-digit format on the day.
I create a few useful js functions for date conversions and use those in my applications.
There's a very nice library to manage date in JS.
Try this.
You'll pretty much have to format it yourself, yeah.
var curDate = new Date();
var year = curDate.getFullYear();
var month = curDate.getMonth() + 1;
var date = curDate.getDate();
if (month < 10) month = "0" + month;
if (date < 10) date = "0" + date;
var dateString = year + "-" + month + "-" + date;
It's a bit long, but it'll work (:
add jquery ui plugin in your page.
function DateFormate(dateFormate, dateTime) {
return $.datepicker.formatDate(dateFormate, dateTime);
};
Just another option, which I wrote:
DP_DateExtensions Library
Not sure if it'll help, but I've found it useful in several projects.
Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.
No reason to consider it if you're already using a framework (they're all capable), but if you just need to quickly add date manipulation to a project give it a chance.

Categories

Resources