Generating a Date from a String with a 'Month-Year' Format

Generating a date from a string with a 'Month-Year' format

You've got it backwards:

library(zoo)
as.yearmon(date, format="%b-%y")
# [1] "Jan 2010" "Feb 2010" "Mar 2010" "Jun 2010" "Jul 2010"

Specify the format in the order in which it appears in the input.


Do not just arbitrarily specify the date format. Note what your attempts were looking for:

  • "%m/%d/%Y" does not work because that is expecting dates in the form of "10/31/2013"
  • "%y-%b" does not work because that is expecting dates in the form of "13-Oct"

Converting year and month (yyyy-mm format) to a date?

Try this. (Here we use text=Lines to keep the example self contained but in reality we would replace it with the file name.)

Lines <- "2009-01  12
2009-02 310
2009-03 2379
2009-04 234
2009-05 14
2009-08 1
2009-09 34
2009-10 2386"

library(zoo)
z <- read.zoo(text = Lines, FUN = as.yearmon)
plot(z)

The X axis is not so pretty with this data but if you have more data in reality it might be ok or you can use the code for a fancy X axis shown in the examples section of ?plot.zoo .

The zoo series, z, that is created above has a "yearmon" time index and looks like this:

> z
Jan 2009 Feb 2009 Mar 2009 Apr 2009 May 2009 Aug 2009 Sep 2009 Oct 2009
12 310 2379 234 14 1 34 2386

"yearmon" can be used alone as well:

> as.yearmon("2000-03")
[1] "Mar 2000"

Note:

  1. "yearmon" class objects sort in calendar order.

  2. This will plot the monthly points at equally spaced intervals which is likely what is wanted; however, if it were desired to plot the points at unequally spaced intervals spaced in proportion to the number of days in each month then convert the index of z to "Date" class: time(z) <- as.Date(time(z)) .

String to date, but only month and year

Let's say your dataframe looks like this

import pandas as pd
df = pd.DataFrame({'date':['2021-01','2021-02','2021-03','2021-04']})

Option 1: dates as pd.Period

df['date_period'] = pd.to_datetime(df['date'],format='%Y-%m').dt.to_period('M')

You can access years and months via

df['year'] = df['date_period'].dt.year
df['month'] = df['date_period'].dt.month

Option 2: dates as integer

df['date_int'] = df['date'].str.replace('-','').astype(int)

You can access years and months via

df['year'] = df['date_int'] // 100
df['month'] = df['date_int'] % 100

Comparison

The result looks like this:

      date date_period  date_int
0 2021-01 2021-01 202101
1 2021-02 2021-02 202102
2 2021-03 2021-03 202103
3 2021-04 2021-04 202104

The second option is approximately twice as fast as the first one:

%timeit pd.to_datetime(df['date'],format='%Y-%m').dt.to_period('M')

703 µs ± 78.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit df['date'].str.replace('-','').astype(int)

304 µs ± 8.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Java: Convert String Date to Month Name Year (MMM yyyy)

Your format must match your input

for 2016-03-20

the format should be (just use a second SimpleDateFormat object)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


Full answer

SimpleDateFormat month_date = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

String actualDate = "2016-03-20";

Date date = sdf.parse(actualDate);

String month_name = month_date.format(date);
System.out.println("Month :" + month_name); //Mar 2016

Using java.time java-8

String actualDate = "2016-03-20";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("MMM yyyy", Locale.ENGLISH);
DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern("MMMM yyyy", Locale.ENGLISH);
LocalDate ld = LocalDate.parse(actualDate, dtf);
String month_name = dtf2.format(ld);
System.out.println(month_name); // Mar 2016
String fullMonthAndYear = dtf3.format(ld);
System.out.println(fullMonthAndYear); // March 2016

How to convert year-month-day date format(eg: 2015-05-12-which is a value retrieved from server) to day-month-year format in android

First you'll need to parse the String into a Date. Then you format the date according to your needs, the example below is an edited version of BalusC's answer from this topic: Change date format in a Java string

String oldstring = "2015-05-12";
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(oldstring);
//Use SimpleDateFormat#format() to format a Date into a String in a certain pattern.

String newstring = new SimpleDateFormat("dd-MM-yyyy").format(date);
System.out.println(newstring); // 12-05-2015

How to Convert (Year, Month, Day) into the Expanded-Year Date Format in Javascript with the Handling for Years 0 to 99

It's a legacy feature that the constructor treats year values from 0 to 99 as 1900 + year, there's no fixing that until the Temporal object is implemented (which might be in ECMAScript 2023 as it seems imminent but it's not in the latest ECMA-262 2022 draft).

As for formatting, ECMAScript has very limited formatting support for dates, which is why there are so many date libraries. You can do a combination of an existing formatting method or create an entirely new one.

E.g. if only positive years are required, then you can leverage toLocaleDateString:

console.log(
new Date()
.toLocaleDateString('en-CA')
.replace(/^(.\d+)/,y => (y<0? '-' : '+')+(''+Math.abs(y))
.padStart(6,'0'))
);

Swift: Date string only has month and year, can I still produce a date?

You almost had it, I tested it on playgrounds use it like this(Just changed the "yyyy-MM" part):

var date = "2001-05"

func stringToDate(_ date: String) -> Date? {
let df = DateFormatter()
df.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
df.dateFormat = "yyyy-MM"
df.date(from: date)

return df.date(from: date)
}

print(stringToDate(date)!)

Java - Format a date given day, month and year integers

If you're concerned about garbage collecting and objects creation, why not keep a single Calendar instance in your class or system, and use it for all formatting purposes using a static / synchronized method?



Related Topics



Leave a reply



Submit